在$ project管道中创建唯一的ObjectId

时间:2019-07-03 18:46:58

标签: mongodb aggregation-framework

我有一个聚合框架查询,该查询将某些文档数据汇总到一个查询集中。不幸的是,由于它与公司相关,因此我无法提供数据。这是管道最后阶段的查询和数据片段:

...
{ $group: { _id: "$SectionId", "Questions": { $addToSet: "$Questions" } } },
{ $unwind: "$Questions" },

返回如下数据:请注意,_id不是唯一的。

{
    "_id" : "Tonometry",
    "Questions" : {
        "MappingId" : "Exophoria",
        "PositiveLabel" : "Positive",
        "NegativeLabel" : "Negative"
    }
},
{
    "_id" : "Tonometry",
    "Questions" : {
        "MappingId" : "Heterophoria",
        "PositiveLabel" : "Positive",
        "NegativeLabel" : "Negative"
    }
},

管道的下一个阶段是:

{
    $project: {
        "_id": 1,
        "id": ObjectId(),
        "SectionId": "$_id",
        "MappingId": "$Questions.MappingId",
        "PositiveLabel": "$Questions.PositiveLabel",
        "NegativeLabel": "$Questions.NegativeLabel",
    }
},

产生:

{
    "_id" : "Tonometry",
    "id" : ObjectId("5d1cf66cf526f23524f865c6"),
    "SectionId" : "Tonometry",
    "MappingId" : "Exophoria",
    "PositiveLabel" : "Positive",
    "NegativeLabel" : "Negative"
},
{
    "_id" : "Tonometry",
    "id" : ObjectId("5d1cf66cf526f23524f865c6"),
    "SectionId" : "Tonometry",
    "MappingId" : "Heterophoria",
    "PositiveLabel" : "Positive",
    "NegativeLabel" : "Negative"
},

我尝试创建一个具有唯一ObjectId的新字段Id,但不幸的是,它仅在所有节点中重复使用相同的ObjectId。这很重要,因为当我尝试使用$out时,它需要一个唯一的_id

如何为每个节点添加唯一的ObjectId?

1 个答案:

答案 0 :(得分:0)

使用 $out 不需要唯一的_id,您可以将 $replaceRoot {{3 }} $mergeObjects 管道之前,这会将Question文档合并到所需的文档中,而没有_id字段和 {{ 3}} 将在新集合中为您创建_id字段:

[
    ....
    { "$group": { "_id": "$SectionId", "Questions": { "$addToSet": "$Questions" } } },
    { "$unwind": "$Questions" },
    { "$replaceRoot": { 
        "newRoot": { 
            "$mergeObjects": [ 
                { "Section": "$_id" }, 
                "$Questions" 
             ] 
        } 
    } },
    { "$out": "new-collection" }
]