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

MongoDB投影指定嵌套字段失败,求解决思路

Fixing MongoDB Projection for Nested Array Fields

Let's break down what's going wrong and how to fix it:

1. The Array Index Mistake

Your biggest issue is the invalid path for the stringValue field. In your sample document, RULES is an array with one element (array indices start at 0, not 1). Using _id.RULES.1.0._Rules.stringValue targets a non-existent element, which throws off the entire projection.

2. Corrected find() Query

Use the correct array index (0) and remove the duplicate CURRENTSTATE entry in your projection:

db.results.find({}, {
  "_id.RULES.0._Rules.stringValue": 1,
  "_id.MYOPERATION": 1,
  "_id.CURRENTSTATE": 1
})

This will return only the desired subfields nested under the _id object:

{
  "_id": {
    "RULES": [{"_Rules": {"stringValue": "Y_RULES"}}],
    "MYOPERATION": 1,
    "CURRENTSTATE": "PROPOSED"
  }
}

3. Flatten Fields to Top-Level (Optional)

If you prefer to extract these fields as top-level properties instead of keeping them nested under _id, use the aggregation framework's $project stage:

db.results.aggregate([
  {
    $project: {
      ruleStringValue: "$_id.RULES.0._Rules.stringValue",
      myOperation: "$_id.MYOPERATION",
      currentState: "$_id.CURRENTSTATE",
      _id: 0 // Exclude the original _id field if you don't need it
    }
  }
])

Result:

{
  "ruleStringValue": "Y_RULES",
  "myOperation": 1,
  "currentState": "PROPOSED"
}

Why Your Original Query Failed

The invalid array index (1.0) meant MongoDB couldn't resolve that field, but since you were targeting subfields of _id (which is included in results by default), it ended up falling back to returning the entire _id object (and any other top-level fields present). Fixing the index tells MongoDB exactly which fields to include in the projection.

内容的提问来源于stack exchange,提问作者HVA

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:01:02