【发布时间】:2020-07-07 12:57:45
【问题描述】:
嗨:我在用聚合查询替换 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']}
我的目标是获得与原生聚合相同的列表。
这是因为我要“区分”的表达式有一些计算数据我不能直接放入 distinct
样本数据:
[
{
"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"
}
}
]
【问题讨论】:
-
Aggregate返回一个对象数组,因此您无法获得像['square','triangle','circle']这样的字符串数组。但是,您可以获得的最接近的是一个对象数组,其中包含一个包含预期数组的字段,例如[{ _id: ['square','triangle','circle'] }]。您可以通过使用另一个$group来实现这一点
标签: mongodb aggregation-framework distinct