mongodb聚合中的$replaceRoot [英] $replaceRoot in mongodb aggregation

查看:37
本文介绍了mongodb聚合中的$replaceRoot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的收藏:

{
    "_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"
    }
}

帮助.谢谢.

推荐答案

你可以尝试下面的聚合使用 $replaceRoot

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" }}
])

这篇关于mongodb聚合中的$replaceRoot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆