我的文档结构如下:
{
"_id" : NumberLong("80000000012"),
[...]
"categories" : [{
"parent" : "MANUFACTURER",
"category" : "Chevrolet"
}, {
"parent" : "MISCELLANEOUS",
"category" : "Miscellaneous"
}],
[...]
}
我正在尝试为每个“父”字段获取所有“类别”字段的明确列表。我试图利用聚合框架来执行以下查询:
db.posts_temp.aggregate(
{$unwind : '$categories'},
{$match : {'categories.parent' : 'MISCELLANEOUS'}},
{$project : {
'_id' : 0,
parent : '$categories.parent',
category : '$categories.category'
}
},
{
$group : {
_id : '$parent',
category : {$addToSet : '$category'}
}
}
);
运行此查询会返回以下错误:
{
"errmsg" : "exception: $unwind: value at end of field path must be an array",
"code" : 15978,
"ok" : 0
}
这似乎与查询的组部分有关,因为当我删除它时,查询运行正常,但显然,数据不是我想要的。
答案 0 :(得分:0)
我刚试过在我的mongo实例上执行上面的聚合查询。这是我的3个文档,每个文档都有一个包含两个嵌套文档数组的类别的键。
这是我的数据:
{
"_id" : ObjectId("512d5252b748191fefbd4698"),
"categories" : [
{
"parent" : "MANUFACTURER",
"category" : "Chevrolet"
},
{
"parent" : "MISCELLANEOUS",
"category" : "Miscellaneous"
}
]
}
{
"_id" : ObjectId("512d535cb748191fefbd4699"),
"categories" : [
{
"parent" : "MANUFACTURER",
"category" : "Chevrolet"
},
{
"parent" : "MISCELLANEOUS",
"category" : "Pickup"
}
]
}
{
"_id" : ObjectId("512d536eb748191fefbd469a"),
"categories" : [
{
"parent" : "MANUFACTURER",
"category" : "Toyota"
},
{
"parent" : "MISCELLANEOUS",
"category" : "Miscellaneous"
}
]
}
以下是我运行的聚合查询:
db.posts_temp.aggregate( {$unwind:'$categories'} , {$match: {'categories.parent':'MISCELLANEOUS'}}, {$project:{'_id':0, parent: '$categories.parent', category:'$categories.category'}}, {$group:{_id:'$parent', category:{$addToSet:'$category'}}})
结果如下:
{
"result" : [
{
"_id" : "MISCELLANEOUS",
"category" : [
"Pickup",
"Miscellaneous"
]
}
],
"ok" : 1
}
如果我的数据与您的数据之间存在一些差异,请与我们联系。
CSharpie