MongoDB查询嵌入式文档时如何扁平化投影指定字段?
find() Method Got it, let's solve this. You want to pull that nested instrumentRanges.flute.minPitch up to the top level as minPitch in your find() results, no extra map() or client-side processing needed. Here's how to do it:
Working Query (MongoDB 4.4+)
Starting in MongoDB 4.4, the projection parameter in find() supports aggregation-style field expressions. You can directly map the nested field to a top-level key like this:
db.scoreFacts.find( {"instrumentRanges.flute.minPitch": {$gte: 0, $lte:56}}, { "_id": 1, "minPitch": "$instrumentRanges.flute.minPitch" } )
This will return exactly what you're expecting:
{ "_id" : "Bach_Brandenburg5_Mov1.xml", "minPitch" : 50 }
Why Your Original Query Didn't Work
Your initial projection {"instrumentRanges.flute.minPitch": 1} tells MongoDB to include that specific nested field, but it preserves the original hierarchy. MongoDB doesn't automatically flatten nested fields unless you explicitly map them to top-level keys.
For Older MongoDB Versions (Pre-4.4)
If you're stuck on a version before 4.4, you'll need to use the aggregation pipeline (which is still a server-side operation, no client-side map() required). It's not strictly find(), but it's the closest equivalent for older versions:
db.scoreFacts.aggregate([ { $match: {"instrumentRanges.flute.minPitch": {$gte: 0, $lte:56}} }, { $project: { "_id": 1, "minPitch": "$instrumentRanges.flute.minPitch" } } ])
But if you can use MongoDB 4.4 or later, the first find() solution is perfect—it keeps everything within the find() method as you requested.
内容的提问来源于stack exchange,提问作者Arman

