mongodb - mongodb 聚合中的 $replaceRoot

标签 mongodb mongodb-query aggregation-framework

我有一个这样的集合:

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

下面的结构就是我想要的:

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

我试过这个聚合操作:

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

但是那undefined不是我想要的结构:

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

帮助。谢谢。

最佳答案

您可以使用 $replaceRoot 尝试以下聚合

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

关于mongodb - mongodb 聚合中的 $replaceRoot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53059357/

相关文章:

mongodb - 查询Mongo中是否有空对象

MongoDB - 在多个字段中查找所有搜索字符串单词

mongodb - 仅返回嵌套数组中匹配的子文档元素

mongodb - 通过 mongodb River 在 elasticsearch 中创建索引的映射未生效

mongodb - pymongo - ifnull 替换整个对象而不是特定字段

Mongodb聚合(月)查询将 "missing fields"设置为零

Mongodb 计数数组组合

mongodb - 在 Mongoose 中使用连接和过滤器进行查询

mongodb - 在 mongodb 集合中查找最旧/最年轻的帖子

arrays - 按 $lookup 字段排序