【问题标题】:Projection on nested object mongodb find query嵌套对象 mongodb 查找查询上的投影
【发布时间】:2022-01-05 08:51:21
【问题描述】:

如何在mongodb find查询中获取投影中的嵌套对象。

[
  {
    "apikey": 1,
    "meta": {
      "region": {
        "country": "India",
        "city": "bangalore",
        "pincode": 560067
      },
      "address": {
        "houseNo": "G/C 42 Whitefield boulavourd",
        "landmark": "whitefield boulavourd"
      }
    }
  },
  {
    "apikey": 2,
    "meta": {
      "region": {
        "country": "Germaany",
        "city": "Munich",
        "pincode": 80297
      },
      "address": {
        "houseNo": "Zweibrückenstraße 12",
        "landmark": "Zweibrückenstraße 12"
      }
    }
  }
]

我试图获取 apikey 2 的区域。我尝试在下面查找查询 我尝试查找查询,即

db.collection.find({
    "apikey": "2"
  },
  {
    "projection": {
      "_id": 0,
      "apikey": 1,
      "meta.region": 1
    }
})

我收到错误,关于不能在排除投影中包含字段 meta.region。 有没有其他方法可以解决这个问题。 我想要输出,

[
    {
        "apikey":2,
        "region": {
            "country": "Germaany",
            "city": "Munich",
            "pincode": 80297
        }
    }
]

这是mongoplayground

【问题讨论】:

    标签: mongodb find projection nested-object


    【解决方案1】:

    删除projection(包装)级别。

    db.collection.find({
      apikey: 2
    },
    {
      "_id": 1,
      "apikey": "$apikey",
      "region": "$meta.region"
    })
    

    Sample Mongo Playground

    【讨论】:

    • 它正在工作,谢谢:)
    猜你喜欢
    • 2021-01-28
    • 2016-02-14
    • 2021-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多