【问题标题】:How to projection element in array field of MongoDb collection?如何在 MongoDb 集合的数组字段中投影元素?
【发布时间】:2017-03-21 04:27:38
【问题描述】:

MongoDb 集合示例(人):

{
    "id": "12345",
    "schools": [
                {
                    "name": "A",
                    "zipcode": "12345"
                },
                {
                    "name": "B",
                    "zipcode": "67890"
                }
            ]
}

期望的输出:

{
    "id": "12345",
    "schools": [
                {
                    "zipcode": "12345"
                },
                {
                    "zipcode": "67890"
                }
            ]
}

我目前检索全部的部分代码:

collection.find({}, {id: true, schools: true})

我正在查询整个集合。但我只想返回学校元素的邮政编码部分,而不是其他字段(因为实际的学校对象可能包含更多我不需要的数据)。我可以在代码中检索所有并删除那些不需要的字段(如学校的“名称”),但这不是我想要的。我想做一个 MongoDb 查询。

【问题讨论】:

    标签: arrays mongodb projection


    【解决方案1】:

    您可以使用点符号来投影嵌入在数组中的文档中的特定字段。

    db.collection.find({},{id:true, "schools.zipcode":1}).pretty()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-24
      • 2016-03-26
      • 2023-03-31
      相关资源
      最近更新 更多