MongoDB查询:如何仅获取fruits集合中episode_number=2的movies数据?
Got it, let's fix this for you! The problem with your current queries is that they're identifying which documents contain a matching movies element, but they're returning the entire document instead of just the specific movie entry you want. Here are two straightforward ways to get only the episode_number: "2" data:
Method 1: Use the Aggregation Framework (Flexible for Multiple Matches)
If you might have multiple matching entries in the movies array later, or want more control over filtering, the aggregation pipeline is the way to go. It first targets the right documents, then filters the array to keep only what you need:
db.fruits.aggregate([ // Step 1: Find documents that have at least one movie with episode_number "2" { $match: { "movies.episode_number": "2" } }, // Step 2: Filter the movies array to retain only the matching entry { $project: { movies: { $filter: { input: "$movies", cond: { $eq: ["$$this.episode_number", "2"] } } }, _id: 0 // Optional: Remove this line if you need to keep the document _id } } ])
This will return a result where the movies array only contains the episode 2 entry, nothing else.
Method 2: Use Projection with the Positional Operator (Simple for Single Matches)
If you're certain there's only one matching entry in the movies array (like in your sample data), you can use MongoDB's positional $ operator in the projection stage to directly return the first matching element:
db.fruits.find( { "movies.episode_number": "2" }, // Match the document { "movies.$": 1, _id: 0 } // Project only the matching array element ).pretty()
This is shorter and works great for single matches—just note that if there were multiple entries with episode_number: "2", it would only return the first one.
Why Your Original Queries Didn't Work
- When you use
$elemMatchin the query filter (not projection), it's just telling MongoDB "find documents where the movies array has at least one element that matches this condition"—it doesn't modify what gets returned. - Using
"movies.episode_number": "2"as the query does the same thing: it finds the right documents, but without a projection, MongoDB returns the full document by default.
内容的提问来源于stack exchange,提问作者Niraj

