我想将具有一条记录的mongo集合解聚合,其中包含一个大的大型列表,而是在另一个集合中表示为多个记录。对于记录中未包含在长数组中的变量,这将意味着在复制到新集合时将每个新记录重复到arary之上的顶层。
我拥有的是:
> db.current.showOne()
{"name" : "thing",
"othervar" : 1,
"longcollection" : [
{"first": 1,
"second":2},
{"first": 3,
"second":4},
{"first": 5,
"second":6},
... etc...
{"first": 10000,
"second":10001}
]
}
我想要的是:
> db.new.find().limit(5000).pretty()
{"name" : "thing",
"othervar" : 1,
"longcollection" :
{"first": 1,
"second":2}
},
{"name" : "thing",
"othervar" : 1,
"longcollection" :
{"first": 3,
"second":4}
},
{"name" : "thing",
"othervar" : 1,
"longcollection" :
{"first": 5,
"second":6}
},
{"name" : "thing",
"othervar" : 1,
"longcollection" :
{"first": 7,
"second":8}
}
...等。
每条记录唯一的信息位于“longcollection”变量中,该变量现在是字典,而不是数组。所有新记录都会重复其他信息,与“longcollection”相同,而不是在其内部。
我认为这是一种解包或放松。 copyTo()和unwrap / aggregation的语法组合是什么让我在这里?我对mongodb的javascript和聚合方面仍然有点新意。
答案 0 :(得分:4)
您应该可以使用简单的$unwind
执行此操作对于上面的示例,您可以使用:
db.current.aggregate({$unwind: "$longcollection"})
这会给你一个这样的结果:
{
result: : [
{
"_id" : ObjectId(...),
"name": xxxx,
"othervar": yyyyy,
"longcollection" : {
"first": 1,
"second":2
}
},
{
"_id" : ObjectId(...),
"name": yyyy,
"othervar": zzzz,
"longcollection" : {
"first": 3,
"second":4
}
}],
"ok" : 1
}
要停止评论中显示的重复_id消息,您应该可以使用:
db.current.aggregate({$project : {_id: 0, name: 1, othervar: 1, longcollection: 1}}, {$unwind: "$longcollection"})