mongodb 为每个检索到的文档添加计数器 [英] mongodb add counter to each retrieved document
问题描述
嘿,有没有办法向从 mongo 检索到的每个文档添加一个计数器?
Hey is there a way to add to each document retrieved from mongo a counter?
假设我们在 mongo 中有用户:{_id, name}.我想全部获取它们,并为每个检索到的文档添加一个计数器字段,并在获取文档时增加它.
So lets say we have users : {_id, name} in mongo . I want to fetch them all and to each retrieved document I want to add a counter field and increase it as I fetch the docs.
所以结果是
users : [{_id: "some_id_1", name: "john", counter: 1}, {_id: "some_id_2", name: "bob", counter: 2]
所以这个计数器字段会动态生成?
so this counter field would be generated on the fly ?
推荐答案
为了完成前面的 3 个答案,我写了另一个答案.
I write another answer in order to complete the 3 previous ones.
我对这三个答案进行了一些(简单的)基准测试.
I realized some (simple) benchmarkings on these three answers.
数据集:10000 个文档,如下所示:
Dataset : 10000 documents like the following :
{
"_id" : "5e7b55cb911ef7ebdfd72c08",
"name" : "Dominguez"
}
我循环运行了 3 个聚合集 1000 次.
I ran the 3 aggregations set 1000 times in a loop.
var results=[];
for(i=0;i<1000;i++){
var before = new Date();
tmp_res_matthPen=db.testing.aggregate(aggregation_mpenicaud);
var after = new Date();
var mpe = after-before;
var before = new Date();
tmp_res_prasad=db.testing.aggregate(aggregation_prasad);
var after = new Date();
var pra = after-before;
var before = new Date();
tmp_res_valijon=db.testing.aggregate(aggregation_valijon);
var after = new Date();
var val = after-before;
results.push({"pra":pra,"val":val,"mpe":mpe});
}
db.results.insert(results);
这是提供答案的平均值(以毫秒为单位):
"mpe" : 7.725,
"val" : 15.441,
"pra" : 14.911
但是...查看 Valijon 的回答,我注意到 $sort 阶段在这里都不是很有用,因为没有问(并且 _id 字段通常已经根据时间按 _id 生成排序).有些我尝试从管道中删除它们.
BUT ... Looking at the Valijon's answer, i noticed that both $sort stage are not very useful here, as not asked (and _id field is often already sorted by _id generation based on time). Some i try to remove them from pipeline.
"mpe" : 7.399,
"val" : 7.149,
"pra" : 13.541
并在所有管道中的 _id 上添加 $sort 阶段(此处 _id 充当索引字段)
And adding a $sort stage on _id in all pipelines (here _id acts as an indexed field)
"mpe" : 17.518,
"val" : 16.166,
"pra" : 23.078
最后,我按名称排序,因为它没有编入索引并且是随机生成的.
And finally, i sort by name, as it is not indexed and randomly generated.
"mpe" : 16.858,
"val" : 14.27,
"pra" : 24.777
这篇关于mongodb 为每个检索到的文档添加计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!