$replaceRoot in mongodb aggregation

我是研究僧i 提交于 2020-01-30 08:10:13

问题


I have a collection like this:

{
    "_id" : ObjectId("5bd1686ba64b9206349284db"),
    "type" : "Package",
    "codeInstances" : [ 
        {
            "name" : "a",
            "description" : "a"          
        }, 
        {
            "name" : "b",
            "description" : "b1"
        }, 
        {
            "name" : "b",
            "description" : "b2"
        }
    ]
}
{
    "_id" : ObjectId("5bd16ab8a64b92068d485054"),
    "type" : "Package",
    "codeInstances" : [ 
        {
            "name" : "a",
            "description" : "a"          
        }, 
        {
            "name" : "b",
            "description" : "b3"
        }
    ]
}

The following structure is what I want:

{
      "name" : "b",
      "description" : "b1"
}, 
{
      "name" : "b",
      "description" : "b1"
}, 
{
      "name" : "b",
      "description" : "b3"
}

I tried this aggregate operations:

db.getCollection('t_system_code').aggregate([
  {"$unwind":"$codeInstances"},
  {$match:{"codeInstances.name":"b","type" : "Package"}},
  {"$project":{"codeInstances":1,"_id":0}}
]);

But thatundefineds not the structure I want:

{
    "codeInstances" : {
        "name" : "b",
        "description" : "b1"
    }
}
{
    "codeInstances" : {
        "name" : "b",
        "description" : "b2"
    }
}
{
    "codeInstances" : {
        "name" : "b",
        "description" : "b3"
    }
}

Help. Thank you.


回答1:


You can try below aggregation using $replaceRoot

db.collection.aggregate([
  { "$match": { "codeInstances.name": "b", "type": "Package" }},
  { "$unwind": "$codeInstances" },
  { "$match": { "codeInstances.name": "b", "type": "Package" }},
  { "$replaceRoot": { "newRoot": "$codeInstances" }}
])



回答2:


You just need to project for name and description instead of whole codeInstances. Check below

db.collection.aggregate([
  { $unwind: "$codeInstances" },
  { $match: { "codeInstances.name": "b", "type": "Package" }},
  { $project: {
      "name": "$codeInstances.name",
      "description": "$codeInstances.description",
      "_id": 0
  }}
])

Output:

[
  { "description": "b1", "name": "b" },
  { "description": "b2", "name": "b" },
  { "description": "b3", "name": "b" }
]


来源:https://stackoverflow.com/questions/53059357/replaceroot-in-mongodb-aggregation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!