mongoDB:使用递增字段值聚合

时间:2016-01-11 06:43:14

标签: javascript mongodb

我需要将带有嵌套文档的集合转换为带有父引用的模型树结构。新文档应该有一个递增值的字段,从每个文档的1开始。

这就是我的结构的样子:

{
    "_id" : "sdaGREsfRdfGdFdwG",
    "docTitle" : "Document 1",
    "group" : [
        {
            "id" : "cdPhkTpMXi8z6TqMT"
            "title" : "title 1",
            "data" : [
                {
                    "id" : "Nkspf5kKfPo3axeJA",
                    "some" : "data",
                    "other" : "things",
                    "and" : "so on",    
                },
                {
                    "id" : "vyjgkuNXRN9KkCd5o",
                    "some" : "data",
                    "other" : "things",
                    "and" : "so on",    
                }
            ],

        },
        {
            "id" : "TuibXPe5qMvqdMW6q"
            "title" : "title 2",
            "data" : [
                {
                    "id" : "f5L5zsSNRSQKWoAXL",
                    "some" : "data",
                    "other" : "things",
                    "and" : "so on",    
                },
                {
                    "id" : "Ca8ncFgq83RoeD8he",
                    "some" : "data",
                    "other" : "things",
                    "and" : "so on",    
                },
            ],

        }
    ]
}

如您所见,有一个组数组,我想将其转换为单个文档:

{
    "_id" : "cdPhkTpMXi8z6TqMT"
    "title" : "title 1",
    "type" : "group",
    "order": 1,
    "parent" : "sdaGREsfRdfGdFdwG"
},
{
    "_id" : "TuibXPe5qMvqdMW6q"
    "title" : "title 2",
    "type" : "group",
    "order": 2,
    "parent" : "sdaGREsfRdfGdFdwG"
}

我使用aggregate执行此操作:

db.myCol.aggregate([{$unwind:"$group"}, 
    {$project:{_id:"$group.id", title:"$group.title", 
               parent:"$_id", type:{$literal:"group"}}},
    { $out : "target" }
]);

但我不知道如何设置具有递增值的订单字段。对于每个主文档,此递增值应该从1开始。

1 个答案:

答案 0 :(得分:2)

好。尝试使用$(:not("#getLocation")).click(function(){ if($("#getLocation").show()==true){ $("#getLocation").hide(); } });

includeArrayIndex: "arrayIndex"

详细了解{ $unwind: { path: <field path>, includeArrayIndex: <string>, preserveNullAndEmptyArrays: <boolean> } } here

编辑:你的例子应该是这样的

$unwind