Find a document with ObjectID in MongoDB?



To find a document with Objectid in MongoDB, use the following syntax −

db.yourCollectionName.find({"_id":ObjectId("yourObjectIdValue")}).pretty();

To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −

> 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")
}

Display all documents from a collection with the help of find() method. The query is as follows −

> db.findDocumentWithObjectIdDemo.find().pretty();

The following is the output −

{ "_id" : ObjectId("5c90e4384afe5c1d2279d69b"), "UserName" : "Larry" }
{
   "_id" : ObjectId("5c90e4444afe5c1d2279d69c"),
   "UserName" : "Mike",
   "UserAge" : 23
}
{
   "_id" : ObjectId("5c90e4704afe5c1d2279d69d"),
   "UserName" : "Carol",
   "UserAge" : 26,
   "UserHobby" : [
      "Learning",
      "Photography"
   ]
}

Case 1 − Here is the query to find a document with ObjectId in MongoDB.

> db.findDocumentWithObjectIdDemo.find({"_id":ObjectId("5c90e4704afe5c1d2279d69d")}).pretty();

The following is the output −

{
   "_id" : ObjectId("5c90e4704afe5c1d2279d69d"),
   "UserName" : "Carol",
   "UserAge" : 26,
   "UserHobby" : [
      "Learning",
      "Photography"
   ]
}

Case 2 − Here is the query to find another document with ObjectId in MongoDB.

The query is as follows −

> db.findDocumentWithObjectIdDemo.find({"_id": ObjectId("5c90e4444afe5c1d2279d69c")}).pretty();

The following is the output −

{
   "_id" : ObjectId("5c90e4444afe5c1d2279d69c"),
   "UserName" : "Mike",
   "UserAge" : 23
}

Advertisements