我能否通过 id 从 MongoDB 检索多个文档?
是的,要通过 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" }
广告