我如何才能从各个级别的子文档中获取一个子文档字段及其所有_id?

时间:2018-06-22 13:49:24

标签: mongodb mongodb-query aggregation-framework spring-data-mongodb

我具有以下文档结构:

{
    clientId: 1001
    buildings: [
        _id: campus1
        rooms: [
            {
                _id: 2001
                name: conference
            },
            {
                _id: 2002
                name: meeting
            },
        ]
    ]
}

我想获得所有房间ID及其父ID的拼合版本:

{
    roomId: 2001
    buildingId: campus1
},
{
    roomId: 2001
    clientId: 1001
},
{
    roomId: 2002
    buildingId: campus1
},
{
    roomId: 2002
    clientId: 1001
}

那将是从房间ID开始,向上一层并打印房间ID和建筑物ID。之后,再次从房间ID开始,但是这次要向上2级,并打印房间ID和客户ID。

有没有办法做到这一点?

到目前为止,我没有得到想要的结果:

db.collection.aggregate(
[
      { $unwind:"$buildings" },
      { $unwind:"$building.rooms" },
    {
        $project: {
            _id: 0,
            client: "$_id",
            building: "$buildings._id",
            room: "$buildings.floors.rooms._id",
        }
    },
    { $unwind:"$room" }
]
)

1 个答案:

答案 0 :(得分:0)

您可以尝试以下汇总

db.collection.aggregate([
  { "$unwind": "$buildings" },
  { "$unwind": "$buildings.rooms" },
  { "$group": {
    "_id": null,
    "firstArray": {
      "$push": {
        "roomId": "$buildings.rooms._id",
        "buildingId": "$buildings._id"
      }
    },
    "secondArray": {
      "$push": {
        "roomId": "$buildings.rooms._id",
        "clientId": "$clientId"
      }
    }
  }},
  { "$project": {
    "data": {
      "$concatArrays": ["$firstArray", "$secondArray"]
    }
  }},
  { "$unwind": "$data" },
  { "$replaceRoot": { "newRoot": "$data" }}
])

或者这个

db.collection.aggregate([
  { "$facet": {
    "firstArray": [
      { "$unwind": "$buildings" },
      { "$unwind": "$buildings.rooms" },
      { "$project": {
        "roomId": "$buildings.rooms._id",
        "buildingId": "$buildings._id",
        "_id": 0
      }}
    ],
    "secondArray": [
      { "$unwind": "$buildings" },
      { "$unwind": "$buildings.rooms" },
      { "$project": {
        "roomId": "$buildings.rooms._id",
        "clientId": "$clientId",
        "_id": 0
      }}
    ]
  }},
  { "$project": {
    "data": {
      "$concatArrays": ["$firstArray", "$secondArray"]
    }
  }},
  { "$unwind": "$data" },
  { "$replaceRoot": { "newRoot": "$data" }}
])

两者都会给出相同的输出

[
  {
    "buildingId": "campus1",
    "roomId": 2001
  },
  {
    "buildingId": "campus1",
    "roomId": 2002
  },
  {
    "clientId": 1001,
    "roomId": 2001
  },
  {
    "clientId": 1001,
    "roomId": 2002
  }
]