mongodb聚合中的$ replaceRoot

时间:2018-10-30 07:32:13

标签: 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}}
]);

但是那未定义我想要的结构:

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

帮助。谢谢。

2 个答案:

答案 0 :(得分:1)

您只需要为<configuration> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <!-- Support multiple-JVM writing to the same log file --> <prudent>true</prudent> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern> <maxHistory>30</maxHistory> <totalSizeCap>3GB</totalSizeCap> </rollingPolicy> <encoder> <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="FILE" /> </root> </configuration> name而不是整个description进行投影。检查下面

codeInstances

输出:

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

答案 1 :(得分:1)

您可以使用$replaceRoot

尝试进行以下汇总
db.collection.aggregate([
  { "$match": { "codeInstances.name": "b", "type": "Package" }},
  { "$unwind": "$codeInstances" },
  { "$match": { "codeInstances.name": "b", "type": "Package" }},
  { "$replaceRoot": { "newRoot": "$codeInstances" }}
])