我想要一个1,000个文档的集合,我通过将1,000个唯一的_id键传递给单个find()查询的$ in运算符来指定。
这比我运行1,000次查找({_ id:})查询要快多少?
答案 0 :(得分:2)
这样的事可以帮到你
//create some data (100k documents)
for(i=0; i<=100000; i++){
db.foo.insert({"_id":i});
}
//generate some ids to search for
var ids = [];
for(i=0; i<=1000; i++){
ids.push(i);
}
//now let's try the two queries
//#1 - 1000 separate find queries
var timer1Start = new Date().getTime(); //start the stopwatch
ids.forEach(function(i){
var result = db.foo.find({"_id":i});
});
var timer1End = new Date().getTime(); //stop the stopwatch
//#2 $in query
var timer2Start = new Date().getTime(); //start the stopwatch
var result = db.foo.find({"_id": {$in: ids}});
var timer2End = new Date().getTime(); //stop the stopwatch
print("Function #1 = " + (timer1Start - timer1End));
print("Function #2 = " + (timer2Start - timer2End));