To search a document in MongoDB by _id, you need to call ObjectId(). Let us first see the syntax
db.yourCollectionName.find({"_id":ObjectId("yourId")}).pretty();
To understand the concept and search a document, let us implement the following query to create a collection with documents
> db.searchDocumentDemo.insertOne({"UserId":1,"UserName":"Larry"}); { "acknowledged" : true, "insertedId" : ObjectId("5c97a8e4330fd0aa0d2fe487") } > db.searchDocumentDemo.insertOne({"UserId":2,"UserName":"Mike"}); { "acknowledged" : true, "insertedId" : ObjectId("5c97a8ea330fd0aa0d2fe488") } > db.searchDocumentDemo.insertOne({"UserId":3,"UserName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5c97a8f1330fd0aa0d2fe489") } > db.searchDocumentDemo.insertOne({"UserId":4,"UserName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5c97a8fa330fd0aa0d2fe48a") } > db.searchDocumentDemo.insertOne({"UserId":5,"UserName":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5c97a901330fd0aa0d2fe48b") } > db.searchDocumentDemo.insertOne({"UserId":6,"UserName":"Sam"}); { "acknowledged" : true, "insertedId" : ObjectId("5c97a911330fd0aa0d2fe48c") }
Following is the query to display all the documents from a collection with the help of find() method
> db.searchDocumentDemo.find().pretty(); This will produce the following output: { "_id" : ObjectId("5c97a8e4330fd0aa0d2fe487"), "UserId" : 1, "UserName" : "Larry" } { "_id" : ObjectId("5c97a8ea330fd0aa0d2fe488"), "UserId" : 2, "UserName" : "Mike" } { "_id" : ObjectId("5c97a8f1330fd0aa0d2fe489"), "UserId" : 3, "UserName" : "David" } { "_id" : ObjectId("5c97a8fa330fd0aa0d2fe48a"), "UserId" : 4, "UserName" : "Chris" } { "_id" : ObjectId("5c97a901330fd0aa0d2fe48b"), "UserId" : 5, "UserName" : "Robert" } { "_id" : ObjectId("5c97a911330fd0aa0d2fe48c"), "UserId" : 6, "UserName" : "Sam" }
Following is the query to search a document in MongoDB by _id. We called the ObjectId() to display the result:
> db.searchDocumentDemo.find({"_id":ObjectId("5c97a901330fd0aa0d2fe48b")}).pretty();
This will produce the following output:
{ "_id" : ObjectId("5c97a901330fd0aa0d2fe48b"), "UserId" : 5, "UserName" : "Robert" }