1

我想要一个包含 1,000 个文档的集合,我通过将 1,000 个唯一 _id 键传递给单个 find() 查询的 $in 运算符来指定它。

这比我运行 1,000 个 find({_id:}) 查询快多少?

4

1 回答 1

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));
于 2013-04-24T15:04:14.890 回答