MongoDB聚合查询将数组分组

时间:2018-01-04 08:33:04

标签: mongodb mongodb-query aggregation-framework

我有一个类似下面的文件:

{ 
    "_id" : ObjectId("5a4c7eedb1016444df846a24"), 
    "questionText" : "Question", 
    "questionType" : "XYZ", 
    "optionsAll" : [
        {
            "answerId" : ObjectId("5a4c7eedb1016444df846a23"), 
            "answerValue" : "", 
            "answerSeq" : NumberInt(1), 
            "other" : false, 
            "ratingOrder" : NumberInt(0), 
            "freeTextResponse" : "I can write anything"
        }, 
        {
            "answerId" : ObjectId("5a4c7eedb1016444df846a23"), 
            "answerValue" : "", 
            "answerSeq" : NumberInt(1), 
            "other" : false, 
            "ratingOrder" : NumberInt(0), 
            "freeTextResponse" : "I can write anything"
        }, 
        {
            "answerId" : ObjectId("5a4c7eedb1016444df846a23"), 
            "answerValue" : "", 
            "answerSeq" : NumberInt(1), 
            "other" : false, 
            "ratingOrder" : NumberInt(0), 
            "freeTextResponse" : "I can't write anything"
        }
    ], 
    "optionsUnique" : [
        {
            "_id" : ObjectId("5a4c7eedb1016444df846a23"), 
            "_class" : "com.Answer", 
            "answerSeq" : NumberInt(1), 
            "answerValue" : "", 
            "expected" : false, 
            "other" : false, 
            "selected" : false, 
            "version" : NumberLong(0)
        }
    ], 
    "activityId" : ObjectId("5a4c7eedb1016444df846a26")
}

我想在本文档中再添加一个字段,即#34; freeTextResponses"这将包含" freeTextResponse"而且它的数量。如下所示"

"freeTextResponses" : [
                [
                    2.0, 
                    {
                        "freeTextResponse":"I can write anything"
                    }
                ], 
                [
                    1.0, 
                    {
                        "freeTextResponse":"I can't write anything"
                    }
                ]
            ]

我知道我们可以使用mongodb聚合查询来做到这一点,但我找不到符合我要求的那个。任何帮助将受到高度赞赏

1 个答案:

答案 0 :(得分:0)

您需要使用$set,这不会替换您的文档,但会更新它。

db.mycollection.update(
   {questionType: "XYZ"}, // filter which documents to update
   {$set: { // what add to the filtered documents 
      "freeTextResponses" : [
                [
                    2.0, 
                    {
                        "freeTextResponse":"I can write anything"
                    }
                ], 
                [
                    1.0, 
                    {
                        "freeTextResponse":"I can't write anything"
                    }
                ]
            ]
   });

此外,如果您要向freeTextResponses数组添加元素,则应使用$push