Mongo - 不同和聚合之间的等价



嗨:在用聚合查询替换 mongo 独特的"本机"函数时,我遇到了一些问题。

就我而言,我的查询是这样的:

db.collection.distinct('stuff.shape')

然后 mongo 返回一个数组,其中包含不同的 object.field 值,例如

['square','triangle','circle']

但与聚合双倍

db.collection.aggregate([
{   $match:{ 'stuff.shape':{$exists: true} }  },
{   $group:{ '_id': '$stuff.shape'}   }
])

返回许多元素,例如

{'_id':['triangle']}
{'_id':['square']}
{'_id':['circle']}

我的目标是获得与本机聚合相同的列表。

这是因为我想"区分"的表达式有一些计算数据,我不能直接放入不同

示例数据:

[
{
"type": "obligation",
"stuff": {
"name": "must-turn-right",
"shape": "circle"
}
},
{
"type": "information",
"stuff": {
"name": "town_name",
"shape": "square"
}
},
{
"type": "obligation",
"stuff": {
"name": "yeld",
"shape": "triangle"
}
},
{
"type": "danger",
"stuff": {
"name": "beware_of_cattle",
"shape": "triangle"
}
}
]

链接到Mongoplaygroud

正如 @thammada.ts 已经说过的,不可能从aggregate函数中获取等效于distinct函数输出的字符串数组。

通过在聚合管道中添加额外的$group阶段,可以创建一个聚合查询,该查询将一个具有非重复值的文档作为文档中的数组返回:

db.collection.aggregate([
{   $match:{ 'stuff.shape':{$exists: true} }  },
{   $group:{ '_id': '$stuff.shape'}   },
{   $group:{ '_id': null, 'shape': {$push: '$_id'}}}
])

给出输出

[{
"_id": null,
"shape": [
"square",
"circle",
"triangle"
]
}]

聚合管道返回文档。如果需要字段值数组,则需要在应用程序中执行该转换。

最新更新