您可以使用$in运算符在MongoDB中查找ID列表。为了理解这个概念,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.findListOfIdsDemo.insertOne({"StudentName":"Carol","StudentAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ecadd2f684a30fbdfd575") } > db.findListOfIdsDemo.insertOne({"StudentName":"Bob","StudentAge":25}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ecae42f684a30fbdfd576") } > db.findListOfIdsDemo.insertOne({"StudentName":"David","StudentAge":22}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ecaed2f684a30fbdfd577") } > db.findListOfIdsDemo.insertOne({"StudentName":"John","StudentAge":20}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ecaf82f684a30fbdfd578") } > db.findListOfIdsDemo.insertOne({"StudentName":"Mike","StudentAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ecb092f684a30fbdfd579") }
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.findListOfIdsDemo.find().pretty();
以下是输出-
{ "_id" : ObjectId("5c8ecadd2f684a30fbdfd575"), "StudentName" : "Carol", "StudentAge" : 21 } { "_id" : ObjectId("5c8ecae42f684a30fbdfd576"), "StudentName" : "Bob", "StudentAge" : 25 } { "_id" : ObjectId("5c8ecaed2f684a30fbdfd577"), "StudentName" : "David", "StudentAge" : 22 } { "_id" : ObjectId("5c8ecaf82f684a30fbdfd578"), "StudentName" : "John", "StudentAge" : 20 } { "_id" : ObjectId("5c8ecb092f684a30fbdfd579"), "StudentName" : "Mike", "StudentAge" : 23 }
这是通过ID列表查找的查询-
> var listOfIds = ['5c8ecae42f684a30fbdfd576', '5c8ecaf82f684a30fbdfd578']; > var documentIds = listOfIds.map(function(myId) { return ObjectId(myId); }); > db.findListOfIdsDemo.find({_id: {$in: documentIds }}).pretty();
以下是输出-
{ "_id" : ObjectId("5c8ecae42f684a30fbdfd576"), "StudentName" : "Bob", "StudentAge" : 25 } { "_id" : ObjectId("5c8ecaf82f684a30fbdfd578"), "StudentName" : "John", "StudentAge" : 20 }