要在MongoDB中查找带有Objectid的文档,请使用以下语法-
db.yourCollectionName.find({"_id":ObjectId("yourObjectIdValue")}).pretty();
为了理解上述语法,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.findDocumentWithObjectIdDemo.insertOne({"UserName":"Larry"}); { "acknowledged" : true, "insertedId" : ObjectId("5c90e4384afe5c1d2279d69b") } > db.findDocumentWithObjectIdDemo.insertOne({"UserName":"Mike","UserAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5c90e4444afe5c1d2279d69c") } > db.findDocumentWithObjectIdDemo.insertOne({"UserName":"Carol","UserAge":26,"UserHobby":["Learning","Photography"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c90e4704afe5c1d2279d69d") }
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.findDocumentWithObjectIdDemo.find().pretty();
以下是输出-
{ "_id" : ObjectId("5c90e4384afe5c1d2279d69b"), "UserName" : "Larry" } { "_id" : ObjectId("5c90e4444afe5c1d2279d69c"), "UserName" : "Mike", "UserAge" : 23 } { "_id" : ObjectId("5c90e4704afe5c1d2279d69d"), "UserName" : "Carol", "UserAge" : 26, "UserHobby" : [ "Learning", "Photography" ] }
情况1-这是在MongoDB中查找具有ObjectId的文档的查询。
> db.findDocumentWithObjectIdDemo.find({"_id":ObjectId("5c90e4704afe5c1d2279d69d")}).pretty();
以下是输出-
{ "_id" : ObjectId("5c90e4704afe5c1d2279d69d"), "UserName" : "Carol", "UserAge" : 26, "UserHobby" : [ "Learning", "Photography" ] }
情况2-这是在MongoDB中查找具有ObjectId的另一个文档的查询。
查询如下-
> db.findDocumentWithObjectIdDemo.find({"_id": ObjectId("5c90e4444afe5c1d2279d69c")}).pretty();
以下是输出-
{ "_id" : ObjectId("5c90e4444afe5c1d2279d69c"), "UserName" : "Mike", "UserAge" : 23 }