MongoDB find by ID

In this MongoDB tutorial, we will understand how to find documents by id in MongoDB. We will cover this topic with different operations and examples. Additionally, we will also discuss the following topics:

  • MongoDB find by id query
  • MongoDB find where id equals
  • MongoDB find where id in the list
  • MongoDB findone without id
  • MongoDB find specific id
  • MongoDB find where id in an array
  • MongoDB compass find by id
  • MongoDB find by id not working
  • MongoDB find by id using python

MongoDB find by id query

In MongoDB, you can use the find() method to retrieve the documents from the collection.

Syntax:

db.collection.find(query, projection)

This query selects documents in a collection and returns a cursor to the selected documents.

ParameterTypeDescription
querydocuments Optional, specifies selection filter using the
query operators. To find all documents in a collection, drop this parameter or pass an
empty documents ( { } ).
projectiondocumentsOptional, Defines the fields to return in the documents that match the query filter. To return
all fields in the matching documents.

Returns: The find() method “returns documents” method is returning a cursor to the documents.

Also, check: Import JSON and insert JSON into MongoDB

MongoDB find where id equals

In this topic, you will learn to find the documents of a particular id equals.

Now we will understand this with the help of an example.

Example:

The following documents were inserted into the animal collection.

db.animal.insertMany([
{
        "_id" : 101,
        "animalArray" : [
                "cow",
                "dog"
        ]
},
{
        "_id" : 102,
        "animalArray" : [
                "cow",
                "dog",
                "lizard"
        ]
},
{
        "_id" : 103,
        "animalArray" : [
                "cow",
                "dog",
                "lizard",
                "lion",
                "cat"
        ]
},
{
        "_id" : 104,
        "animalArray" : [
                "cow",
                "dog",
                "lion",
                "cat"
        ]
}
])

After inserting the documents into the collection, apply the below query to find where the id equals.

db.animal.find({ _id: 101 })

Here, the find() method will return the documents where the id is 101.

MongoDB find where id equals
MongoDB find where id equals

We have successfully retrieved the documents where the id is equal.

Read: MongoDB compare two fields

MongoDB find where id in the list

In this topic, you will learn to find the documents where the id is in the list.

We will cover this with an example where we will insert some documents into the collection. After that, we will covert the id field into the list and retrieve the documents.

Example:

The following documents were inserted into the data collection.

db.data.insertMany([
{ "content": "How are you?", "likes": 60, "year": 2015 },
{ "content": "After death life?", "likes": 60, "year": 2015 },
{ "content": "took other apple", "likes": 60, "year": 2015 }
])

After that retrieve the documents by using the find() method.

db.data.find()

Here, the find() will retrieve all the documents of the data collection.

MongoDB find by id
MongoDB find by id

Now, we will apply the below query to find through the list of ids-

# store the id into list
var listOfIds = ["616534e4016e7b648abb7faa", "616534e4016e7b648abb7fab", "616534e4016e7b648abb7fac"]

# Each document visited by the cursor
var documentIds = listOfIds.map(function(myId) { return ObjectId(myId); });

# Retrive all the documents by their Id
db.data.find({_id: {$in: documentIds }}).pretty()

Here, we have stored id into the list listOfIds variable. After that, we have used the map() function to apply to each document visited by the cursor and store it into the documentIds variable.

The find() method will retrieve the documents and the $in operator is used to select the documents where the value of a field equals any value in the specified array.

MongoDB find where id in the list
MongoDB find where id in the list

We have successfully retrieved the documents where id in the list.

Read: MongoDB sort by field

MongoDB findone without id

In this topic, you will learn to find documents without specifying the id. MongoDB provides the findOne() method that is used to find the document without specifying the id.

Example:

The following documents were inserted into the relation collection.

db.relation.insertMany([
{ "subject": "Joe", "content": "best friend", "likes": 60, "year": 2015, "language": "english" }
{ "subject": "Dogs", "content": "Cats", "likes": 30, "year": 2015, "language" : "english" }
{ "subject": "Cats", "content": "Rats", "likes": 55, "year": 2014, "language": "english" }
{ "subject": "Rats", "content": "Joe", "likes": 75, "year": 2014, "language": "english" }
])

After that, we will apply the below query to find one documents without specifying the id.

db.relation.findOne()

Here, we didn’t specify any id in the findOne() method and it will only return the first document of the collection.

MongoDB findone without id
MongoDB findone without id

Read: MongoDB sort by date

MongoDB find specific id

As we know MongoDB automatically assigns the unique id to the documents. In this topic, you will learn to find the document of a specific id.

So, you have to specify the id in the find() method to find the document of the specific id. let us understand with the help of an example.

Example:

The following documents were inserted into the address collection.

db.address.insertMany([
  { "name": "Amy", "address": "Apple st 652, USA"},
  { "name": "Hannah", "address": "Mountain 21, Canada"},
  { "name": "Michael", "address": "Valley 345, United States"},
  { "name": "Sandy", "address": "Ocean blvd 2, Australia"},
  { "name": "Betty", "address": "Green Grass 1, New Zealand"},
  { "name": "Richard", "address": "Sky st 331, United Kingdom"}
])

After inserting the documents, we will apply the below query to find the document of the specific id.

db.address.find( { _id: ObjectId("61a4bcf2219d8fb582a3ba26") })

Here, we have defined the specific id in the find() method to retrieve the specific document.

MongoDB find the document of the specific id
MongoDB find the document of the specific id

We have successfully retrieved the document of the specific id.

Read: MongoDB backup and restore

MongoDB find where id in an array

In this topic, you will learn to find the documents where the id is in an array. Let’s get understand this with the help of an example.

Example:

The following documents were inserted into the members’ collection.

db.members.insert({
     "_id": 1,
     "Friends": [
             {
                "_id" : 2,
                "Name" : "Bob"
             },
             {
                "_id" : 3,
                "Name" : "Charlotte"
             },
             {
                "_id" : 4,
                "Name" : "Bob"
             }
        ]
})

After that, we will apply the below query to find the documents where the id is in an array.

db.members.find( { "Friends._id": 2} ).pretty()

In the find() method, we have defined the id that is in an array and retrieved the document accordingly.

MongoDB find where id in an array
MongoDB find where id in an array

We have successfully retrieved the document by their id where the id field is in an array.

Read: How does MongoDB create a collection

MongoDB compass find by id

In this topic, you will learn to find the documents by their id using MongoDB compass. MongoDB Compass reviews your documents and displays documents within our collections through an automatic GUI.

Example:

In this example, we will find the documents according to their id using MongoDB compass.

Now follow the below step to understand the example.

  • Open the MongoDB compass and connect to the server.
  • Now you have to select the existing database and collection where you find out the documents as per their id.
MongoDB compass find by id
MongoDB compass find by id

Here, we have selected the artists’ collection of the Company database.

  • Click on OPTIONS drop down list button
  • Apply condition to find the documents by their id.
{ _id: 5 }       # write in FILTER section

The above query will return the documents where the id is 5.

  • After that, click on FIND to retrieve the document as per their condition.
MongoDB compass find document by their id
MongoDB compass find the document by their id

We have successfully retrieved the documents by their id using MongoDB compass.

Read: Export MongoDB to CSV

MongoDB find by id not working

In this topic, we will discuss the reasons when find by id not working. There could be some reason so when you are executing any query or command you have to remember these things:

  • You have to be very focused while executing any query, sometimes we forget to close brackets.
  • Use the proper function or method that could avoid getting errors.

MongoDB find by id using python

In this topic, you will learn to find a particular document by their id using python.

Now, we will cover this with the help of an example and find documents by id using python.

Example:

In the example, we will use an existing database and collection and find documents by their id accordingly:

import pymongo

# creating a MongoClient object and connect with the host
myclient = pymongo.MongoClient("mongodb://127.0.0.1:27017")

# accessing the database
mydb = myclient["Company"]

# accessing the collection of the database
mycol = mydb["artists"]

# compare the field of same documents 
result = mycol.find({ "_id": 3})
for find_id in result:
    print(find_id)

In this above code first, we have imported the python pymongo library to use the MongoDB functionality in python. After that, we have used MongoClient class to make the connection with the server.

We have used the existing database and collection Company, artists respectively. And, we have used the find() function, define parameter id 3 to find the document by their id.

MongoDB find by id using python
MongoDB find by id using python

We have successfully retrieved the documents by id using python.

You may also like to read the following articles on MongoDB.

So, in this tutorial, we have understood to find documents by their id in MongoDB. Additionally, we have also discussed the following topics:

  • MongoDB find by id query
  • MongoDB find where id equals
  • MongoDB find where id in the list
  • MongoDB findone without id
  • MongoDB find specific id
  • MongoDB find where id in an array
  • MongoDB compass find by id
  • MongoDB find by id not working
  • MongoDB find by id using python