• Post author:
  • Post category:MongoDB
  • Post last modified:May 9, 2024
  • Reading time:8 mins read
You are currently viewing Search Object by its ObjectId in Mongo console

How to search an object by its ObjectId in MongoDB console? Each document in MongoDB is identified by a unique _id field, which is typically represented by an ObjectId. In the article, we will figure out ways to search for an object by its ObjectId in the MongoDB console. Certainly, there are a few different approaches for searching for an object by its ObjectId which we will cover aswell.

Advertisements

Let’s assume the collection student with the four documents. Note that these documents don’t contain the _id field.


#Create collection
db.student.insertMany([
    { 
        name: "Harry",
        age: 18 ,
        degree: "IT"
    },
    { 
        name: "James",
        age: 21 ,
        degree: "Computer"
    },
    { 
        name: "Nina",
        age: 20 ,
        degree: "Software Engineering"
    },
    { 
        name: "Olive",
        age: 19 ,
        degree: "BBA"
    }
])

When we execute the above insertion query, the system automatically adds the _id field as ObjectID that will be used below to search Object by its ObjectID. The ObjectID looks like this.

search by objectid in Mongodb

1. Using the find() to Search an Object by its ObjectId

Use the find() method to search for an object by its ObjectId in MongoDB, this function takes _id with ObjectId() as value. Here, we are using the find method with the ObjectId constructor. Note that we need to pass the ObjectId as a string to the ObjectId constructor. In the following example, we search for an object with the ObjectId 64158e800f1ca44b2c095847 in the student collection.


# Usage of find() method
db.student.find({_id: ObjectId("64158e800f1ca44b2c095847")});

The record that matches with the specified ObjectID is retrieved in the output.

search by _id in Mongodb

2. Using the Condition to Search an Object by its ObjectId

Sometimes we also required to search for an object by its ObjectId with a conditional operator. The find() method is used that takes a query object with the ObjectId and any conditional operator. Here in the example, we used the $gt conditional operator that finds all records with an _id greater than an ObjectId 64158e800f1ca44b2c095848.


# Usage of conditional operator
db.student.find({_id: {$gt: ObjectId("64158e800f1ca44b2c095848")}})

Thus, the above query returned two records with an _id greater than the specified ObjectId.

3. Using the getTimestamp() method to search an object by its ObjectId

The getTimestamp() method is another way to extract the timestamp from the ObjectId and search for objects that were created before or after a certain date. Here in the example, we have used the getTimeStamp() method on the ObjectID. The query will return records in the collection with an ObjectId created after the date March 18, 2023 as the $gt operator is specified.


# Usage of getTimestamp() method
db.student.find({_id: {$gt: 
  ObjectId(Math.floor((new Date('2023-03-18')).getTime()/1000).toString(16) + "0000000000000000")
}})

 As we can see all the records by ObjectId are yielded in the output by the getTimestamp() method. 

search by objectid in Mongodb

4. Using the variable to store ObjectId

You can also store the ObjectId value in a variable and pass it to the MongoDB find() method that includes the ObjectId stored in a variable. In this example, the myObjectId function creates a new ObjectId with the specified value and stores it in the variable myObjectId. Then, the find() method searches for documents with the _id field matching the variable myObjectId.


# Usage of Variable method
var myObjectId = ObjectId("64158e800f1ca44b2c095849");
db.student.find({_id: myObjectId});

As you can seen, the query outputs the record with an _id field that matches the myObjectId variable.

5. Using the ObjectID.isValid() method

Moreover, using the ObjectId.isValid() method of MongoDB we can search for an object by its ObjectId. The ObjectId.isValid() method checks if the string is a valid ObjectId string. Consider the example, the ObjectId.isValid() method here is called inside the if-else method to check if the myId is a valid ObjectId string. If it is, then the find() method search records with the _id field matching the objectId variable. If the myId is not a valid ObjectId string, an error message will be printed to the console.


# Usage of ObjectId.isValid() method
var myId = "64158e800f1ca44b2c09584a";
if (ObjectId.isValid(myId)) {
  db.student.find({_id: ObjectId(myId)});
} else {
  console.log("Invalid ObjectId");
}

The record is fetched with the specified ObjectId as the ObjectId string is valid. 

search by objectid in Mongodb

6. Conclusion

In conclusion, searching for records by their ObjectId is a common task in MongoDB. We have explored methods with the example implementation that can search for records by their ObjectId. Keep this in mind, that the _id field in MongoDB is unique and represents the primary key of the records, so it is important to use the correct _id field when searching for records.

More details about the ObjectId can be found here.