diff --git a/mflix/README-JAVA-SPRING.md b/mflix/README-JAVA-SPRING.md index 988fc49..d73a717 100644 --- a/mflix/README-JAVA-SPRING.md +++ b/mflix/README-JAVA-SPRING.md @@ -5,9 +5,9 @@ This is a full-stack movie browsing application built with Java Spring Boot and ## Project Structure ``` -├── README-JAVA-SPRING.md +├── README.md ├── client/ # Next.js frontend (TypeScript) -└── server/java-spring/ # Java Spring Boot backend +└── server/ # Java Spring Boot backend ├── src/ ├── pom.xml ├── .env.example @@ -21,6 +21,8 @@ This is a full-stack movie browsing application built with Java Spring Boot and - **MongoDB Atlas cluster or local deployment** with the `sample_mflix` dataset loaded - [Load sample data](https://www.mongodb.com/docs/atlas/sample-data/) - **Maven** (included via Maven Wrapper) +- **Voyage AI API key** (For MongoDB Vector Search) + - [Get a Voyage AI API key](https://www.voyageai.com/) ## Getting Started @@ -29,7 +31,7 @@ This is a full-stack movie browsing application built with Java Spring Boot and Navigate to the Java Spring server directory: ```bash -cd server/java-spring +cd server ``` Create a `.env` file from the example: @@ -42,20 +44,34 @@ Edit the `.env` file and set your MongoDB connection string: ```env # MongoDB Connection -MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/?retryWrites=true&w=majority +# Replace with your MongoDB Atlas connection string or local MongoDB URI +MONGODB_URI=mongodb+srv://:@.mongodb.net/sample_mflix?retryWrites=true&w=majority + +# Voyage AI Configuration +# API key for Voyage AI embedding model (required for Vector Search) +VOYAGE_API_KEY=your_voyage_api_key # Server Configuration +# Port on which the Spring Boot application will run PORT=3001 # CORS Configuration +# Allowed origin for cross-origin requests (frontend URL) +# For multiple origins, separate with commas CORS_ORIGIN=http://localhost:3000 + +# Optional: Enable MongoDB Search tests +# Uncomment the following line to enable Search tests +# ENABLE_SEARCH_TESTS=true ``` -**Note:** Replace `username`, `password`, and `cluster` with your actual MongoDB Atlas credentials. +**Note:** Replace `username`, `password`, and `cluster` with your +actual MongoDB Atlas credentials. Replace `your_voyage_api_key` with +your key. ### 2. Start the Backend Server -From the `server/java-spring` directory, run: +From the `server` directory, run: ```bash # Using Maven Wrapper (recommended) @@ -100,11 +116,15 @@ Open your browser and navigate to: ## Features -- **Browse Movies:** View a paginated list of movies from the sample_mflix dataset -- **Search:** Full-text search using MongoDB Search -- **Filter:** Filter movies by genre, year, rating, and more -- **Movie Details:** View detailed information about each movie -- **Aggregations:** Complex data aggregations and analytics +- **Browse Movies:** View a paginated list of movies from the + sample_mflix dataset +- **CRUD Operations:** Create, read, update and delete movies by using + the MongoDB Java driver +- **Search:** Search movies with filters by using MongoDB Search +- **Vector Search:** Search movie plots with similar search terms by + using MongoDB Vector Search +- **Aggregations:** View data aggregations and analytics built with + aggregation pipelines ## Development @@ -119,7 +139,7 @@ The Java Spring Boot backend uses: To run tests: ```bash -cd server/java-spring +cd server ./mvnw test ``` diff --git a/mflix/README-JAVASCRIPT-EXPRESS.md b/mflix/README-JAVASCRIPT-EXPRESS.md index fa79f86..39bd092 100644 --- a/mflix/README-JAVASCRIPT-EXPRESS.md +++ b/mflix/README-JAVASCRIPT-EXPRESS.md @@ -1,16 +1,211 @@ # JavaScript Express.js MongoDB Sample MFlix Application -[TODO: Add intro] +This is a full-stack movie browsing application built with Express.js and Next.js, demonstrating MongoDB operations using the `sample_mflix` dataset. The application showcases CRUD operations, aggregations, and MongoDB Search using the native MongoDB Node.js driver. + +## Project Structure ``` ├── README.md -├── client/ # Next.js frontend -└── server/ # Express.js backend +├── client/ # Next.js frontend (TypeScript) +└── server # Express.js backend + ├── src/ + ├── package.json + ├── .env.example + └── tsconfig.json ``` +## Prerequisites + +- **Node.js 22** or higher +- **MongoDB Atlas cluster or local deployment** with the `sample_mflix` dataset loaded + - [Load sample data](https://www.mongodb.com/docs/atlas/sample-data/) +- **npm** (included with Node.js) +- **Voyage AI API key** (For MongoDB Vector Search) + - [Get a Voyage AI API key](https://www.voyageai.com/) + ## Getting Started -[TODO: Add getting started instructions explaining how to set connection string, start server, start client, etc.] +### 1. Configure the Backend + +Navigate to the Express server directory: + +```bash +cd server +``` + +Create a `.env` file from the example: + +```bash +cp .env.example .env +``` + +Edit the `.env` file and set your MongoDB connection string: + +```env +# MongoDB Connection +# Replace with your MongoDB Atlas connection string or local MongoDB URI +MONGODB_URI=mongodb+srv://:@.mongodb.net/sample_mflix?retryWrites=true&w=majority + +# Voyage AI Configuration +# API key for Voyage AI embedding model (required for Vector Search) +VOYAGE_API_KEY=your_voyage_api_key + +# Server Configuration +PORT=3001 +NODE_ENV=development + + +# CORS Configuration +# Allowed origin for cross-origin requests (frontend URL) +# For multiple origins, separate with commas +CORS_ORIGIN=http://localhost:3000 + +# Optional: Enable MongoDB Search tests +# Uncomment the following line to enable Search tests +# ENABLE_SEARCH_TESTS=true +``` + +**Note:** Replace ``, ``, and `` with +your actual MongoDB Atlas credentials. Replace `your_voyage_api_key` with +your key. + +### 2. Install Backend Dependencies + +From the `server` directory, run: + +```bash +npm install +``` + +### 3. Start the Backend Server + +From the `server` directory, run: + +```bash +# Development mode with hot reloading +npm run dev +``` + + +Or for production mode, run: + +```bash +npm run build +npm start +``` + +The server will start on `http://localhost:3001`. You can verify it's running by visiting: +- API root: http://localhost:3001/ +- API documentation (Swagger UI): http://localhost:3001/api-docs + +### 4. Configure and Start the Frontend + +Open a new terminal and navigate to the client directory: + +```bash +cd client +``` + +Install dependencies: + +```bash +npm install +``` + +Start the development server: + +```bash +npm run dev +``` + +The Next.js application will start on `http://localhost:3000`. + +### 5. Access the Application + +Open your browser and navigate to: +- **Frontend:** http://localhost:3000 +- **Backend API:** http://localhost:3001 +- **API Documentation:** http://localhost:3001/api-docs + +## Features + +- **Browse Movies:** View a paginated list of movies from the + sample_mflix dataset +- **CRUD Operations:** Create, read, update and delete movies by using + the MongoDB Node.js driver +- **Search:** Search movies with filters by using MongoDB Search +- **Vector Search:** Search movie plots with similar search terms by + using MongoDB Vector Search +- **Aggregations:** View data aggregations and analytics built with + aggregation pipelines + +## Development + +### Backend Development + +The Express.js backend uses: +- **Express.js 5** for REST API +- **MongoDB Node.js Driver** for database operations +- **TypeScript** for type safety +- **Swagger** for API documentation +- **Jest** for testing + +To run tests: + +```bash +cd server +npm test +``` + +To run tests with coverage: + +```bash +cd server +npm run test:coverage +``` + +### Frontend Development + +The Next.js frontend uses: +- **React 19** with TypeScript +- **Next.js 16** with App Router +- **Turbopack** for fast development builds + +#### Development Mode + +For active development with hot reloading and fast refresh: + +```bash +cd client +npm run dev +``` + +This starts the development server on `http://localhost:3000` with Turbopack for fast rebuilds. + +#### Production Build + +To create an optimized production build and run it: + +```bash +cd client +npm run build # Creates optimized production build +npm start # Starts production server +``` + +The production build: +- Minifies and optimizes JavaScript and CSS +- Optimizes images and assets +- Generates static pages where possible +- Provides better performance for end users + +#### Linting + +To check code quality: + +```bash +cd client +npm run lint +``` ## Issues diff --git a/mflix/client/README.md b/mflix/client/README.md index 811c099..8c46ce4 100644 --- a/mflix/client/README.md +++ b/mflix/client/README.md @@ -1,37 +1,49 @@ -# MongoDB Sample MFlix Frontend +# Next.js MFlix Frontend Application -This is a [Next.js](https://nextjs.org) frontend application that demonstrates MongoDB operations by connecting to an Express.js backend. The application showcases Server Side Rendering (SSR) and displays movie data from the sample_mflix database. +This is a Next.js frontend application that demonstrates a modern movie browsing experience by connecting to a backend API. The application showcases Server Side Rendering (SSR), responsive design, and interactive features while displaying movie data from the MongoDB sample_mflix dataset. -## Features +## Project Structure -- **Movies Page** (`/movies`): Displays a paginated grid of movies with Server Side Rendering -- **Pagination**: Navigate through movies with previous/next controls and adjustable page sizes -- **Movie Details Page** (`/movie/[id]`): Shows comprehensive movie information including plot, cast, ratings, and more -- **Movie Cards**: Shows movie title, poster, year, rating, and genres with navigation to details -- **Navigation**: Sticky navigation bar with links to home and movies pages -- **Responsive Design**: Works on desktop and mobile devices -- **Error Handling**: Graceful fallbacks for missing posters, API errors, and not-found movies -- **Loading States**: Professional loading indicators and skeleton screens during data fetching -- **SEO Optimized**: Dynamic metadata generation for movie pages and pagination +``` +client/ +├── README.md +├── package.json +├── next.config.ts +├── tsconfig.json +├── .env.example +└── app/ + ├── layout.tsx # Root layout with navigation + ├── page.tsx # Home page + ├── globals.css # Global styles + ├── movies/ # Movies listing page + ├── movie/[id]/ # Individual movie details + ├── aggregations/ # Data aggregations page + ├── components/ # Reusable UI components + ├── lib/ # API utilities and constants + └── types/ # TypeScript type definitions +``` ## Prerequisites -1. **Express Backend**: The Express server must be running on `http://localhost:3001` -2. **MongoDB Database**: The backend must be connected to a MongoDB instance with the sample_mflix dataset -3. **Node.js**: Version 18 or higher +- **Backend API Server**: The backend server must be running on `http://localhost:3001` +- **MongoDB Database**: The backend must be connected to a MongoDB instance with the `sample_mflix` dataset loaded + - [Load sample data](https://www.mongodb.com/docs/atlas/sample-data/) +- **Node.js 18** or higher +- **npm** (included with Node.js) ## Getting Started -### 1. Environment Configuration +### 1. Configure the Environment -Copy the environment example file and configure your API URL: +Copy the environment example file: ```bash cp .env.example .env.local ``` -Edit `.env.local` and update the API_URL if needed: -```bash +Edit `.env.local` and update the API URL if needed: + +```env API_URL=http://localhost:3001 ``` @@ -47,113 +59,33 @@ npm install npm run dev ``` -Open [http://localhost:3000](http://localhost:3000) with your browser to see the application. - -### 4. View the Movies - -Navigate to [http://localhost:3000/movies](http://localhost:3000/movies) to see the movies grid with data from the MongoDB sample_mflix database. - -**Pagination Features:** -- Use the **Previous/Next** buttons to navigate between pages -- Change the **page size** (10, 20, or 50 movies per page) using the dropdown selector -- URL parameters support direct linking: `?page=2&limit=10` -- Click the "Get Details" button on any movie card to view comprehensive movie information - -## API Integration - -The application connects to the Express backend using Server Side Rendering: - -- **Movies API**: `GET /api/movies` - Fetches movie data with pagination support (`limit` and `skip` parameters) -- **Movie Details API**: `GET /api/movies/:id` - Fetches detailed information for a specific movie -- **Pagination**: Smart pagination that detects available pages by requesting `limit + 1` movies -- **Error Handling**: Graceful fallbacks when the API is unavailable -- **Type Safety**: TypeScript interfaces matching the backend data structure - -## Available Scripts - -- `npm run dev` - Starts the development server with Turbopack -- `npm run build` - Builds the application for production -- `npm run start` - Starts the production server -- `npm run lint` - Runs ESLint for code quality - -## Project Structure - -``` -client/ -├── app/ -│ ├── movie/ -│ │ └── [id]/ -│ │ ├── page.tsx # Movie details page with SSR -│ │ ├── loading.tsx # Loading skeleton for details -│ │ ├── error.tsx # Error boundary for details -│ │ └── not-found.tsx # 404 page for invalid movies -│ ├── movies/ -│ │ ├── page.tsx # Movies page with SSR -│ │ └── loading.tsx # Loading component -│ ├── components/ -│ │ └── MovieCard/ # Reusable movie card component -│ ├── lib/ -│ │ ├── api.ts # API functions -│ │ └── constants.ts # App constants and routes -│ ├── types/ -│ │ └── movie.ts # TypeScript type definitions -│ ├── layout.tsx # Root layout with navigation -│ └── page.tsx # Home page -├── .env.example # Environment variables template -└── .env.local # Local environment configuration -``` - -## Development Notes - -### Server Side Rendering - -The movies page uses Next.js Server Side Rendering (SSR) to fetch data on the server before sending the page to the client. This provides: - -- **Better SEO**: Search engines can index the movie content -- **Faster Initial Load**: Users see content immediately -- **Fresh Data**: Movie data is fetched on each page request - -### Type Safety - -The application uses TypeScript interfaces that match the backend MongoDB document structure: - -```typescript -interface Movie { - _id: string; - title: string; - year?: number; - poster?: string; - genres?: string[]; - imdb?: { - rating?: number; - }; -} -``` - -### Error Handling +The Next.js application will start on `http://localhost:3000`. -- **API Errors**: Shows fallback message when the backend is unavailable -- **Missing Posters**: Displays placeholder for movies without poster images -- **Network Issues**: Graceful degradation with empty state +### 4. Access the Application -## Learn More +Open your browser and navigate to: +- **Frontend:** http://localhost:3000 +- **Movies Page:** http://localhost:3000/movies +- **Aggregations:** http://localhost:3000/aggregations -To learn more about the technologies used: - -- [Next.js Documentation](https://nextjs.org/docs) - Learn about Next.js features and API -- [MongoDB Node.js Driver](https://mongodb.github.io/node-mongodb-native/) - Backend database integration -- [TypeScript](https://www.typescriptlang.org/) - Type safety and development experience +## Features -## Deployment +- **Browse Movies:** View a paginated list of movies from the sample_mflix dataset with server-side rendering +- **Movie Details:** Access comprehensive movie information including plot, cast, ratings, and metadata +- **CRUD Operations:** Create, read, update, and delete movies +- **Search & Filters:** Search movies with various filters and sorting + options using MongoDB Search +- **Vector Search:** Find movies with similar plot descriptions using + MongoDB Vector Search +- **Data Aggregations:** View analytics and insights built with MongoDB aggregation pipelines -### Development -The application is configured to work with a local Express backend on port 3001. +## Issues -### Production -For production deployment: +If you have problems running the sample app, please check the following: -1. Update `API_URL` in your environment configuration -2. Build the application: `npm run build` -3. Start the production server: `npm start` +- [ ] Verify that you have started the backend server on port 3001. +- [ ] Verify that the backend is connected to MongoDB with the sample_mflix dataset. +- [ ] Verify that you have set the correct API_URL in your `.env.local` file. +- [ ] Verify that you have no firewalls blocking access to ports 3000 or 3001. -The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. +If you have verified the above and still have issues, please [open an issue](https://github.com/mongodb/docs-sample-apps/issues/new/choose) on the source repository `mongodb/docs-sample-apps`. diff --git a/mflix/client/app/components/SearchMovieModal/SearchMovieModal.tsx b/mflix/client/app/components/SearchMovieModal/SearchMovieModal.tsx index 45bfcb4..642ec0b 100644 --- a/mflix/client/app/components/SearchMovieModal/SearchMovieModal.tsx +++ b/mflix/client/app/components/SearchMovieModal/SearchMovieModal.tsx @@ -28,7 +28,7 @@ export interface SearchParams { cast?: string; limit?: number; skip?: number; - search_operator?: 'must' | 'should' | 'mustNot' | 'filter'; + searchOperator?: 'must' | 'should' | 'mustNot' | 'filter'; // Vector Search fields q?: string; } @@ -42,7 +42,7 @@ interface SearchFormData { writers: string; cast: string; limit: string; - search_operator: 'must' | 'should' | 'mustNot' | 'filter'; + searchOperator: 'must' | 'should' | 'mustNot' | 'filter'; // Vector Search fields q: string; } @@ -56,7 +56,7 @@ const getInitialFormData = (): SearchFormData => ({ writers: '', cast: '', limit: '20', - search_operator: 'must', + searchOperator: 'must', // Vector Search fields q: '', }); @@ -115,7 +115,7 @@ export default function SearchMovieModal({ if (formData.searchType === 'mongodb-search') { // Add MongoDB Search specific parameters - searchParams.search_operator = formData.search_operator; + searchParams.searchOperator = formData.searchOperator; searchParams.skip = 0; // Always start from beginning for new search if (formData.plot.trim()) { @@ -316,13 +316,13 @@ export default function SearchMovieModal({ {/* Search Operator */}
-
diff --git a/mflix/client/app/lib/api.ts b/mflix/client/app/lib/api.ts index 4ec0f96..9c77b47 100644 --- a/mflix/client/app/lib/api.ts +++ b/mflix/client/app/lib/api.ts @@ -593,7 +593,7 @@ export async function searchMovies(searchParams: { cast?: string; limit?: number; skip?: number; - search_operator?: 'must' | 'should' | 'mustNot' | 'filter'; + searchOperator?: 'must' | 'should' | 'mustNot' | 'filter'; }): Promise<{ success: boolean; error?: string; movies?: Movie[]; hasNextPage?: boolean; hasPrevPage?: boolean; totalCount?: number }> { try { // Build query parameters @@ -609,7 +609,7 @@ export async function searchMovies(searchParams: { if (searchParams.cast) queryParams.append('cast', searchParams.cast); queryParams.append('limit', limit.toString()); queryParams.append('skip', skip.toString()); - if (searchParams.search_operator) queryParams.append('search_operator', searchParams.search_operator); + if (searchParams.searchOperator) queryParams.append('searchOperator', searchParams.searchOperator); const response = await fetch(`${API_BASE_URL}/api/movies/search?${queryParams}`, { method: 'GET', diff --git a/mflix/server/java-spring/.env.example b/mflix/server/java-spring/.env.example index 9efc711..627b54b 100644 --- a/mflix/server/java-spring/.env.example +++ b/mflix/server/java-spring/.env.example @@ -1,6 +1,6 @@ # MongoDB Connection # Replace with your MongoDB Atlas connection string or local MongoDB URI -MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/?retryWrites=true&w=majority +MONGODB_URI=mongodb+srv://:@.mongodb.net/sample_mflix?retryWrites=true&w=majority # Voyage AI Configuration # API key for Voyage AI embedding model (required for Vector Search) @@ -15,3 +15,6 @@ PORT=3001 # For multiple origins, separate with commas CORS_ORIGIN=http://localhost:3000 +# Optional: Enable MongoDB Search tests +# Uncomment the following line to enable Search tests +# ENABLE_SEARCH_TESTS=true \ No newline at end of file diff --git a/mflix/server/java-spring/src/main/java/com/mongodb/samplemflix/service/MovieService.java b/mflix/server/java-spring/src/main/java/com/mongodb/samplemflix/service/MovieService.java index 159bf54..8221b27 100644 --- a/mflix/server/java-spring/src/main/java/com/mongodb/samplemflix/service/MovieService.java +++ b/mflix/server/java-spring/src/main/java/com/mongodb/samplemflix/service/MovieService.java @@ -85,7 +85,7 @@ public interface MovieService { /** * Finds similar movies using vector search on plot embeddings. - * Demonstrates MongoDB Atlas Vector Search. + * Demonstrates MongoDB Vector Search. * * @param movieId ID of the movie to find similar movies for * @param limit Maximum number of similar movies to return (default: 10, max: 50) diff --git a/mflix/server/java-spring/src/main/java/com/mongodb/samplemflix/service/MovieServiceImpl.java b/mflix/server/java-spring/src/main/java/com/mongodb/samplemflix/service/MovieServiceImpl.java index 3b6ee5a..eb592a0 100644 --- a/mflix/server/java-spring/src/main/java/com/mongodb/samplemflix/service/MovieServiceImpl.java +++ b/mflix/server/java-spring/src/main/java/com/mongodb/samplemflix/service/MovieServiceImpl.java @@ -759,7 +759,7 @@ public List findSimilarMovies(String movieId, Integer limit) { .append("index", "plotEmbeddingIndex") .append("path", "plot_embedding") .append("queryVector", plotEmbedding) - .append("numCandidates", resultLimit * 10) + .append("numCandidates", resultLimit * 20) // We recommend searching 20 times higher than the limit to improve result relevance .append("limit", resultLimit + 1) // +1 to exclude the source movie ); @@ -847,7 +847,7 @@ public List vectorSearchMovies(String query, Integer limit) .append("index", "vector_index") .append("path", "plot_embedding_voyage_3_large") .append("queryVector", queryVector) - .append("numCandidates", resultLimit * 15) // Search more candidates for better results + .append("numCandidates", resultLimit * 20) // We recommend searching 20 times higher than the limit to improve result relevance .append("limit", resultLimit) ); diff --git a/mflix/server/java-spring/src/test/java/com/mongodb/samplemflix/integration/README.md b/mflix/server/java-spring/src/test/java/com/mongodb/samplemflix/integration/README.md index f2083be..a2fc932 100644 --- a/mflix/server/java-spring/src/test/java/com/mongodb/samplemflix/integration/README.md +++ b/mflix/server/java-spring/src/test/java/com/mongodb/samplemflix/integration/README.md @@ -1,12 +1,12 @@ -# Atlas Search Integration Tests +# MongoDB Search Integration Tests -This directory contains integration tests for MongoDB Atlas Search functionality. +This directory contains integration tests for MongoDB Search functionality. ## Overview -The `AtlasSearchIntegrationTest` class tests the Atlas Search endpoints with a real MongoDB Atlas instance. These tests verify that: +The `MongoDBSearchIntegrationTest` class tests the MongoDB Search endpoints with a real MongoDB Atlas instance. These tests verify that: -1. The Atlas Search index is created correctly +1. The MongoDB Search index is created correctly 2. The index becomes ready for use (using polling) 3. The `/search` endpoint returns correct results 4. Pagination works correctly @@ -17,7 +17,7 @@ The `AtlasSearchIntegrationTest` class tests the Atlas Search endpoints with a r These tests require: - **MongoDB Atlas cluster** (not local MongoDB or Testcontainers) -- **Atlas Search capability** enabled on the cluster +- **MongoDB Search capability** enabled on the cluster - **MONGODB_URI** environment variable pointing to your Atlas cluster - **ENABLE_SEARCH_TESTS=true** environment variable to enable the tests @@ -49,10 +49,10 @@ MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/sample_mflix?ret ```bash # Run all integration tests -./mvnw test -Dtest=AtlasSearchIntegrationTest +./mvnw test -Dtest=MongoDBSearchIntegrationTest # Run a specific test -./mvnw test -Dtest=AtlasSearchIntegrationTest#testSearchMoviesByPlot_Success +./mvnw test -Dtest=MongoDBSearchIntegrationTest#testSearchMoviesByPlot_Success ``` ## How the Tests Work @@ -113,7 +113,7 @@ export ENABLE_SEARCH_TESTS=true If the tests fail with "Search index did not become ready within 120 seconds": -1. Check that your cluster has Atlas Search enabled +1. Check that your cluster has MongoDB Search enabled 2. Verify you're using a MongoDB Atlas cluster (not local MongoDB) 3. Check the Atlas UI to see if the index is being created 4. Increase `MAX_INDEX_WAIT_SECONDS` if needed diff --git a/mflix/server/js-express/.env.example b/mflix/server/js-express/.env.example index 027a11e..725cc0d 100644 --- a/mflix/server/js-express/.env.example +++ b/mflix/server/js-express/.env.example @@ -1,12 +1,19 @@ -# MongoDB Configuration -# Replace with your MongoDB Atlas connection string +# MongoDB Connection +# Replace with your MongoDB Atlas connection string or local MongoDB URI MONGODB_URI=mongodb+srv://:@.mongodb.net/sample_mflix?retryWrites=true&w=majority +# Voyage AI Configuration +# API key for Voyage AI embedding model (required for Vector Search) +VOYAGE_API_KEY=your_voyage_api_key + # Server Configuration PORT=3001 NODE_ENV=development -# CORS Configuration (frontend URL) + +# CORS Configuration +# Allowed origin for cross-origin requests (frontend URL) +# For multiple origins, separate with commas CORS_ORIGIN=http://localhost:3000 # Optional: Enable MongoDB Search tests diff --git a/mflix/server/js-express/package.json b/mflix/server/js-express/package.json index 2035bac..151b911 100644 --- a/mflix/server/js-express/package.json +++ b/mflix/server/js-express/package.json @@ -22,7 +22,7 @@ "cors": "^2.8.5", "dotenv": "^17.2.3", "express": "^5.1.0", - "mongodb": "^6.20.0", + "mongodb": "^7.0.0", "swagger-jsdoc": "^6.2.8", "swagger-ui-express": "^5.0.1" }, diff --git a/mflix/server/js-express/src/routes/movies.ts b/mflix/server/js-express/src/routes/movies.ts index a4dbbf9..ed2c9d0 100644 --- a/mflix/server/js-express/src/routes/movies.ts +++ b/mflix/server/js-express/src/routes/movies.ts @@ -122,8 +122,8 @@ router.get("/", asyncHandler(movieController.getAllMovies)); * @swagger * /api/movies/search: * get: - * summary: Search movies using MongoDB Atlas Search - * description: Search movies using MongoDB Atlas Search across multiple fields with compound queries and fuzzy matching. Demonstrates MongoDB Atlas Search capabilities. + * summary: Search movies using MongoDB Search + * description: Search movies using MongoDB Search across multiple fields with compound queries and fuzzy matching. Demonstrates MongoDB Search capabilities. * tags: [Movies] * parameters: * - in: query diff --git a/mflix/server/js-express/src/types/index.ts b/mflix/server/js-express/src/types/index.ts index 5515c75..34e3fc7 100644 --- a/mflix/server/js-express/src/types/index.ts +++ b/mflix/server/js-express/src/types/index.ts @@ -286,7 +286,7 @@ export type RawMovieSearchQuery = { }; /** - * Interface for MongoDB Atlas Search phrase queries + * Interface for MongoDB Search phrase queries */ export interface SearchPhrase { phrase?: { diff --git a/mflix/server/js-express/tests/integration/README.md b/mflix/server/js-express/tests/integration/README.md index c251312..9e7a7da 100644 --- a/mflix/server/js-express/tests/integration/README.md +++ b/mflix/server/js-express/tests/integration/README.md @@ -13,7 +13,7 @@ The integration tests are organized into three main categories: - Automatically skipped if `MONGODB_URI` is not set 2. **MongoDB Search Integration Tests** (`mongodbSearch.integration.test.ts`) - - Tests the MongoDB Atlas Search API endpoint using `supertest` + - Tests the MongoDB Search API endpoint using `supertest` - Makes actual HTTP requests to test the `/api/movies/search` endpoint - Tests search by plot, directors, cast, pagination, and search operators - Automatically skipped if `ENABLE_SEARCH_TESTS` is not set @@ -22,10 +22,10 @@ The integration tests are organized into three main categories: - Tests advanced API endpoints using `supertest` - Makes actual HTTP requests to test: - **Aggregation endpoints**: Movies with comments, statistics by year, directors with most movies - - **Atlas Search endpoint**: Compound queries, phrase matching, fuzzy matching + - **MongoDB Search endpoint**: Compound queries, phrase matching, fuzzy matching - **Vector Search endpoint**: Semantic similarity search using embeddings - Aggregation tests automatically run if `MONGODB_URI` is set - - Atlas Search tests require `ENABLE_SEARCH_TESTS=true` + - MongoDB Search tests require `ENABLE_SEARCH_TESTS=true` - Vector Search tests require `VOYAGE_API_KEY` to be set **Note:** Tests use `describeIntegration`, `describeSearch`, and `describeVectorSearch` wrappers (from `setup.ts` and test files) that automatically skip entire test suites when the required environment variables are not set. @@ -49,7 +49,7 @@ This approach ensures that the API endpoints work correctly from the client's pe - **MONGODB_URI** environment variable must be set - MongoDB instance must be accessible (can be local MongoDB or Atlas) -### Atlas Search Tests +### MongoDB Search Tests - **MongoDB instance** with Search enabled (local MongoDB or Atlas) - **MONGODB_URI** environment variable diff --git a/mflix/server/js-express/tests/integration/advancedEndpoints.integration.test.ts b/mflix/server/js-express/tests/integration/advancedEndpoints.integration.test.ts index 55f9663..71702e2 100644 --- a/mflix/server/js-express/tests/integration/advancedEndpoints.integration.test.ts +++ b/mflix/server/js-express/tests/integration/advancedEndpoints.integration.test.ts @@ -2,7 +2,7 @@ * Advanced Endpoints Integration Tests * * These tests verify the advanced MongoDB API endpoints including: - * - Atlas Search + * - MongoDB Search * - Vector Search * - Aggregation pipelines ($lookup, $group, $unwind) * @@ -322,14 +322,14 @@ describeIntegration("Advanced Endpoints Integration Tests", () => { }); }); -describeSearch("Atlas Search Integration Tests", () => { +describeSearch("MongoDB Search Integration Tests", () => { let testMovieIds: string[] = []; beforeAll(async () => { if (!process.env.ENABLE_SEARCH_TESTS) { console.log(` -⚠️ Atlas Search tests skipped: ENABLE_SEARCH_TESTS environment variable is not set - To run Atlas Search integration tests, set ENABLE_SEARCH_TESTS=true in your .env file +⚠️ MongoDB Search tests skipped: ENABLE_SEARCH_TESTS environment variable is not set + To run MongoDB Search integration tests, set ENABLE_SEARCH_TESTS=true in your .env file Example: ENABLE_SEARCH_TESTS=true npm run test:integration `); return; diff --git a/mflix/server/js-express/tests/integration/mongodbSearch.integration.test.ts b/mflix/server/js-express/tests/integration/mongodbSearch.integration.test.ts index 614a1de..741ad65 100644 --- a/mflix/server/js-express/tests/integration/mongodbSearch.integration.test.ts +++ b/mflix/server/js-express/tests/integration/mongodbSearch.integration.test.ts @@ -1,7 +1,7 @@ /** - * MongoDB Atlas Search API Integration Tests + * MongoDB Search API Integration Tests * - * These tests verify the Atlas Search API endpoints with actual HTTP requests. + * These tests verify the MongoDB Search API endpoints with actual HTTP requests. * The tests require: * - A MongoDB Atlas instance with Search enabled * - MONGODB_URI environment variable @@ -15,7 +15,7 @@ import request from "supertest"; import { app } from "../../src/app"; import { describeSearch } from "./setup"; -describeSearch("MongoDB Atlas Search API Integration Tests", () => { +describeSearch("MongoDB API Integration Tests", () => { describe("GET /api/movies/search - Search by plot", () => { test("should find movies with plot search", async () => { diff --git a/mflix/server/python-fastapi/.env.example b/mflix/server/python-fastapi/.env.example index e25ebf9..59ac463 100644 --- a/mflix/server/python-fastapi/.env.example +++ b/mflix/server/python-fastapi/.env.example @@ -1,4 +1,5 @@ -# MongoDB Configuration +# MongoDB Connection +# Replace with your MongoDB Atlas connection string or local MongoDB URI MONGO_URI="mongodb+srv://:@.mongodb.net/sample_mflix?retryWrites=true&w=majority" MONGO_DB="sample_mflix" @@ -8,4 +9,4 @@ VOYAGE_API_KEY=your_voyage_api_key # CORS Configuration # Comma-separated list of allowed origins for CORS -CORS_ORIGINS="http://localhost:3000,http://localhost:8000" \ No newline at end of file +CORS_ORIGINS="http://localhost:3000,http://localhost:8000" diff --git a/mflix/server/python-fastapi/src/routers/movies.py b/mflix/server/python-fastapi/src/routers/movies.py index 797f7d2..4bcbdbf 100644 --- a/mflix/server/python-fastapi/src/routers/movies.py +++ b/mflix/server/python-fastapi/src/routers/movies.py @@ -118,7 +118,7 @@ async def search_movies( cast: str = Query(default=None), limit:int = Query(default=20, ge=1, le=100), skip:int = Query(default=0, ge=0), - search_operator: str = Query(default="must") + search_operator: str = Query(default="must", alias="searchOperator") ) -> SuccessResponse[SearchMoviesResponse]: search_phrases = [] @@ -345,7 +345,7 @@ async def vector_search_movies( "index": "vector_index", "path": "plot_embedding_voyage_3_large", "queryVector": query_embedding, #2048 - "numCandidates": limit * 15, # Search more candidates for better results + "numCandidates": limit * 20, # We recommend searching 20 times higher than the limit to improve result relevance "limit": limit } }, @@ -482,12 +482,12 @@ async def get_all_movies( title: str = Query(default=None), genre:str = Query(default=None), year:int = Query(default=None), - min_rating:float = Query(default=None), - max_rating:float = Query(default=None), + min_rating:float = Query(default=None, alias="minRating"), + max_rating:float = Query(default=None, alias="maxRating"), limit:int = Query(default=20, ge=1, le=100), skip:int = Query(default=0, ge=0), - sort_by:str = Query(default="title"), - sort_order:str = Query(default="asc") + sort_by:str = Query(default="title", alias="sortBy"), + sort_order:str = Query(default="asc", alias="sortOrder") ): movies_collection = get_collection("movies") filter_dict = {}