我有一个像这样的集合
{
"_id" : ObjectId("53a7fb486201281a1f698fe4"),
"userId" : ObjectId("53a7fade6201281a1f698fd9"),
"magic" : [
{
"power" : 0,
"mana" : 10,
"foo" : null,
"bar" : 150
},
{
"power" : 2,
"mana" : 2,
"foo" : 200,
"bar" : 1
},
]
}
{
"_id" : ObjectId("53a7fb486201281a1f698fe4"),
"userId" : ObjectId("53a7fade6201281a1f698fd9"),
"magic" : [
{
"power" : 20,
"mana" : 210,
"foo" : null,
"bar" : 2150
},
{
"power" : 23,
"mana" : 23,
"foo" : 2004,
"bar" : 14
},
]
}
{
"_id" : ObjectId("53a7fb486201281a1f698fe4"),
"userId" : ObjectId("anotherID"),
"magic" : [
{
"power" : 20,
"mana" : 210,
"foo" : null,
"bar" : 2150
},
{
"power" : 23,
"mana" : 23,
"foo" : 2004,
"bar" : 14
},
]
}
我想创建一个独特的数组“magic of userId ObjectId("53a7fade6201281a1f698fd9")
我确实试过这个
db.myColl.aggregate([
{
'$group': {
_id: {
magic: "$magic",
},
"allmagic": {
$push: "$magic"
},
},
}
]);
结果是我的集合中所有魔法数组的数组myColl
然后我尝试使用$match
db.myColl.aggregate([
{
'$group': {
_id: {
magic: "$magic",
},
"allmagic": {
$push: "$magic"
},
},
$match : { "userId" : ObjectId("53a7fade6201281a1f698fd9") }
}
]);
但我有这个错误
exception: A pipeline stage specification object must contain exactly one field.
。
然后我想在node.js中使用它(我也使用mongoose)
答案 0 :(得分:1)
在聚合框架中使用数组,尤其是要使用$unwind
运算符的文档:
db.myColl.aggregate([
// Match documents for user id first
{ "$match": { "userId": ObjectId("53a7fade6201281a1f698fd9") }},
// Unwind the array
{ "$unwind": "$magic" },
// Group back to a single user document
{ "$group": {
"_id": "$userId",
"magic": { "$addToSet": "$magic" }
}}
])
$addToSet
运算符保留数组的元素"唯一",如果您只想在不删除重复项的情况下进行组合,则使用$push
代替。