返回特定的mongodb嵌入式文档

贾拉蒂夫

我想查询mongodb文件以返回特定文件

假设我有以下文档,并且只想搜索给定房间的特定详细信息。说,我想查询以返回room_num = 210的注释。我该怎么做?

我能够通过db.locations.findOne({“ facility.room.room_num”:room_num})进行查询;我不知道如何只投影房间。概括这个问题,我如何只投影嵌入式文档特定的条目。

我的文档看起来像这样--->

{
  _id: Object("xxx"),
  name: "Campus",
  facilities: [
     { name : "Science",
     rooms : [
          {
             room_num: 210,
             notes: "Chemistry Lab 1",
             Dimension: "x*x"
          },{
             room_num: 120,
             notes: "Chemistry Lab 2",
             Dimension: "x*x"
          }
      ]

    },
    { name : "Arts",
     rooms: [
          {
             room_num: 90,
             notes: "Drawing 1",
             Dimension: "x*x"
          },{
             room_num: 100,
             notes: "Drawing 2",
             Dimension: "x*x"
          }
      ]

    }
  ]
尼尔·伦恩

由于您有一个嵌入式阵列(一个在另一个阵列中),因此您确实可以使用聚合来完成。您只需要执行“双重”展开操作:

db.collection.aggregate([
    { "$unwind": "$facilities" },
    { "$unwind": "$facilities.rooms" },
    { "$match": { "facilities.rooms.room_num": 210 } }
])

如果您真的希望它看起来像原始文档,那么请进一步:

db.collection.aggregate([
    { "$unwind": "$facilities" },
    { "$unwind": "$facilities.rooms" },
    { "$match": { "facilities.rooms.room_num": 210 } },
    { "$group": {
        "_id": "$_id",
        "name": { "$first": "$name" },
        "facName": { "$first": "$facilities.name" },
        "rooms": { "$push": "$facilities.rooms" }
    }},
    { "$group": {
        "_id": "$_id",
        "name": { "$first": "$name" },
        "facities": { "$push": {
            "name": "$facName" ,
            "rooms": "$rooms"
        }}
    }}
])

因此,从您的数据中可以得出以下结果:

{
    "_id" : {
            "0" : "x",
            "1" : "x",
            "2" : "x"
    },
    "name" : "Campus",
    "facities" : [
       {
           "name" : "Science",
           "rooms" : [
               {
                   "room_num" : 210,
                   "notes" : "Chemistry Lab 1",
                   "Dimension" : "x*x"
               }
           ]
       }
    ]
}

或者最后,如果您需要的只是数组的内部房间部分,则只需$project在最后使用一条语句,如第一个示例所示:

db.campus.aggregate([
    { "$unwind": "$facilities" },
    { "$unwind": "$facilities.rooms" },
    { "$match": { "facilities.rooms.room_num": 210 } },
    { "$project": {
        "_id": 0,
        "room_num": "$facilities.rooms.room_num",
        "notes": "$facilities.rooms.notes",
        "Dimension": "$facilities.rooms.Dimension"
    }}
])

结果如下:

{ "room_num" : 210, "notes" : "Chemistry Lab 1", "Dimension" : "x*x" }

那应该清除它。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章