为MongoDB聚合中的字段分配增量编号 [英] Assign an incremental number to a field in a MongoDB aggregation
问题描述
我有一个MongoDB聚合,并且每个文档都有一个像这样的字段(groupNumber):
I have a MongoDB aggregation and each document has a field (groupNumber) like this:
我需要每个groupNumber的每个文档具有不同的编号(可以是1,2,3 ..递增)
I need that each groupNumber has a different number for each document (could be incremental 1,2,3..)
我找到的大多数解决方案都在使用查找" 像这样,但我认为不能在聚合中使用.
Most of the solutions that I had found are using "find" like this one , but I think that cannot be used in an aggregation.
提前谢谢.
推荐答案
您可以通过查找来完成此操作,但是我认为它不能很好地扩展.我认为应该以某种方式将其保留下来,也许 $ out
到另一个集合中,以使数字稳定,并且删除或插入文档不会改变任何其他组的数字.>
You can do this with a lookup, but I don't think it will scale well. I would think this should be persisted in some way, perhaps $out
to another collection, so that the numbers are stable and deleting or inserting a document won't change the numbers for any other group.
db.target.aggregate([
{"$lookup":{
"from":"target",
"as":"looked",
"let":{"srcId":"$_id"},
"pipeline":[
{"$match":{"$expr":{"$lte":["$_id","$$srcId"]}}},
{"$group":{"_id":"null", "cnt":{"$sum":1}}}
]
}},
{"$addFields":{"groupNumber":{"$arrayElemAt":["$looked.cnt",0]}}},
{"$project":{"looked":0}}
])
这篇关于为MongoDB聚合中的字段分配增量编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!