You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB查询嵌入式文档时如何扁平化投影指定字段?

How to Get Flattened Output with MongoDB's 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:44:33