是的,要按ID从MongoDB中检索多个文档,请使用$in运算符。语法如下
db.yourCollectionName.find({_id:{$in:[yourValue1,yourValue2,yourValue3,...N]}});
让我们首先创建一个包含文档的集合:
> db.retrieveMultipleDocsByIdDemo.insertOne({"_id":10,"CustomerName":"John"}); { "acknowledged" : true, "insertedId" : 10 } > db.retrieveMultipleDocsByIdDemo.insertOne({"_id":14,"CustomerName":"Chris"}); { "acknowledged" : true, "insertedId" : 14 } > db.retrieveMultipleDocsByIdDemo.insertOne({"_id":20,"CustomerName":"Robert"}); { "acknowledged" : true, "insertedId" : 20 } > db.retrieveMultipleDocsByIdDemo.insertOne({"_id":25,"CustomerName":"Sam"}); { "acknowledged" : true, "insertedId" : 25 } > db.retrieveMultipleDocsByIdDemo.insertOne({"_id":30,"CustomerName":"Bob"}); { "acknowledged" : true, "insertedId" : 30 } > db.retrieveMultipleDocsByIdDemo.insertOne({"_id":34,"CustomerName":"Carol"}); { "acknowledged" : true, "insertedId" : 34 }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.retrieveMultipleDocsByIdDemo.find().pretty();
这将产生以下输出
{ "_id" : 10, "CustomerName" : "John" } { "_id" : 14, "CustomerName" : "Chris" } { "_id" : 20, "CustomerName" : "Robert" } { "_id" : 25, "CustomerName" : "Sam" } { "_id" : 30, "CustomerName" : "Bob" } { "_id" : 34, "CustomerName" : "Carol" }
以下是按ID从MongoDB中检索多个文档的查询
> db.retrieveMultipleDocsByIdDemo.find({_id:{$in:[10,20,30]}});
这将产生以下输出
{ "_id" : 10, "CustomerName" : "John" } { "_id" : 20, "CustomerName" : "Robert" } { "_id" : 30, "CustomerName" : "Bob" }