假设我有一个如下的文档模型
{
"_id" : "QggaecdDWkZzMmmM8",
"features" : [
{
"language" : "en",
"values" : [
{
"name" : "feature 1",
"values" : [
"test",
"best"
]
},
{
"name" : "feature2",
"values" : [
"guest",
"nest"
]
}
]
}
}
现在我需要运行查询并返回特征的唯一名称和值对。就像一个文档的名称特征 1 带有“test”和最佳值,另一个文档具有相同的键(特征 1 具有不同的值,即“guest”),所以结果将是
name: featuer 1
values: [test, best and guest]
到目前为止,我尝试了以下查询,但最后返回错误
db.getCollection('products').aggregate(
{$unwind: '$features'},
{$group:
{_id: "$features.values.name"},
name: {$addToSet: '$name'}
})
错误信息是
exception: A pipeline stage specification object must contain exactly one field
最佳答案
name 字段应该在小组阶段内,这就是你出错的原因。
试试这个查询:
db.getCollection('products').aggregate([
{
$unwind: '$features'
},
{
$unwind: '$features.values'
},
{
$unwind: '$features.values.values'
},
{
$group: {
_id: "$features.values.name",
values: {$addToSet: '$features.values.values'}
},
}
])
结果:
{ "_id" : "feature2", "values" : [ "nest", "guest" ] }
{ "_id" : "feature 1", "values" : [ "best", "test" ] }
关于mongodb - 对象数组中的 Mongodb 不同值组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40437761/