Mongo - distinct 和 aggregate 之间的等价
Mongo - equivalence between distinct and aggregate
嗨:我在用聚合查询替换 mongo 的不同 'native' 函数时遇到了一些问题。
在我的例子中,我的查询是这样的:
db.collection.distinct('stuff.shape')
mongo 然后 returns 具有不同值 object.field 的数组,例如
['square','triangle','circle']
但与聚合
db.collection.aggregate([
{ $match:{ 'stuff.shape':{$exists: true} } },
{ $group:{ '_id': '$stuff.shape'} }
])
returns 许多元素喜欢
{'_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"
}
}
]
聚合管道returns 文档。如果您想要一个字段值数组,则需要在您的应用程序中执行该转换。
正如@thammada.ts 已经说过的,不可能从 aggregate
函数中得到一个等同于 distinct
函数输出的字符串数组。
通过在聚合管道中添加额外的 $group
阶段,可以创建一个聚合查询,returns 一个文档将不同的值作为文档中的数组:
db.collection.aggregate([
{ $match:{ 'stuff.shape':{$exists: true} } },
{ $group:{ '_id': '$stuff.shape'} },
{ $group:{ '_id': null, 'shape': {$push: '$_id'}}}
])
给出输出
[{
"_id": null,
"shape": [
"square",
"circle",
"triangle"
]
}]
嗨:我在用聚合查询替换 mongo 的不同 'native' 函数时遇到了一些问题。
在我的例子中,我的查询是这样的:
db.collection.distinct('stuff.shape')
mongo 然后 returns 具有不同值 object.field 的数组,例如
['square','triangle','circle']
但与聚合
db.collection.aggregate([
{ $match:{ 'stuff.shape':{$exists: true} } },
{ $group:{ '_id': '$stuff.shape'} }
])
returns 许多元素喜欢
{'_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"
}
}
]
聚合管道returns 文档。如果您想要一个字段值数组,则需要在您的应用程序中执行该转换。
正如@thammada.ts 已经说过的,不可能从 aggregate
函数中得到一个等同于 distinct
函数输出的字符串数组。
通过在聚合管道中添加额外的 $group
阶段,可以创建一个聚合查询,returns 一个文档将不同的值作为文档中的数组:
db.collection.aggregate([
{ $match:{ 'stuff.shape':{$exists: true} } },
{ $group:{ '_id': '$stuff.shape'} },
{ $group:{ '_id': null, 'shape': {$push: '$_id'}}}
])
给出输出
[{
"_id": null,
"shape": [
"square",
"circle",
"triangle"
]
}]