Query on Embedded Documents in MongoDB: Embedded Object Fields & Arrays Fields

MongoDB database contains lots of documents. Sometimes the documents have documents in them. These documents may further contain more documents hence forming a complex structure. 

Querying uncomplicated documents is straightforward and we have already covered how to query MongoDB documents in another article: NodeJS MongoDB Query.

However, the complex structure sometimes results in difficulty in querying. Individuals, especially ones who are new to programming and MongoDB may even have a hard time in the beginning. Here comes this tutorial.

In this tutorial, we will learn to query embedded documents in MongoDB, no matter how big the data is in your database. We will look at several examples to help you learn how to query different types of embedded documents. 

Querying Embedded Documents in MongoDB

In this section, we will try to query two types of embedded documents. The first is the nested document or nested/embedded object field value, and the second is the embedded array field value. If you are not familiar with these teams then do not worry, we will tell you about them as well. Let’s get started.

Setup:

1. Start the MongoDB shell.

2. Execute the following commands to list all the available databases & move into one of them.

show dbs
use droneStore

Here we are using the drone store database which we have already created contains a collection “drones” possess numerous documents for demonstration.

Let us have a look at the documents residing in the collection “drones” before we proceed to the next step. We will be using the pretty() function which is used to format the query results with a proper indentation and produce more readable output.

Following are the documents inside “drones”: 

> db.drones.find({}).pretty()

{
        "_id" : ObjectId("61673f46b34f185eb7b2bf0c"),
        "utility" : [
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Nimbari Gryphon Medeta 65",
        "price" : 77500,
        "weight" : "77 kilograms",
        "additionalDetails" : {
                "material" : "carbon fiber",
                "moreUses" : [
                        "Delivery",
                        "Monitoring or Inspection",
                        "Recreation"
                ]
        }
}
{
        "_id" : ObjectId("61673f46b34f185eb7b2bf0d"),
        "utility" : [
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "X-Strimmer Eye",
        "price" : 23500,
        "weight" : "24 kilograms",
        "additionalDetails" : {
                "material" : "glass fiber",
                "moreUses" : [
                        "Land Inspection",
                        "Water Inspection"
                ]
        }
}
{
        "_id" : ObjectId("61673f46b34f185eb7b2bf0e"),
        "utility" : [
                "Delivery",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Khai Balemosh Shefqa TRX",
        "price" : 120500,
        "weight" : "80 kilograms",
        "additionalDetails" : {
                "material" : "aluminum",
                "moreUses" : [
                        "Monitoring or Inspection",
                        "Land Inspection"
                ]
        }
}
{
        "_id" : ObjectId("61673f46b34f185eb7b2bf0f"),
        "utility" : [
                "Photography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Sifinist Croma AX",
        "price" : 99500,
        "weight" : "97 kilograms",
        "additionalDetails" : {
                "material" : "lithium",
                "moreUses" : [
                        "Videography",
                        "Water Inspection"
                ]
        }
}
{
        "_id" : ObjectId("61673f46b34f185eb7b2bf10"),
        "utility" : [
                "Security",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Drovce Finnifield FR-7",
        "price" : 87600,
        "weight" : "13 kilograms",
        "additionalDetails" : {
                "material" : "polysterene",
                "moreUses" : [
                        "Land Inspection",
                        "Videography"
                ]
        }
}

In the above result, you can see that the documents contained in the collection comprise fields with string values, numerical values, object values, and even arrays inside them, in order to demonstrate querying them.

Querying Embedded Object Fields

Embedded object fields are fields containing JavaScript objects (subdocuments) nested within the main document. Let’s see how to query them.

Example

Below is a query demonstrating querying a nested document or a nested/embedded object field value:

> db.drones.find({"additionalDetails.material": "lithium"}).pretty()
{
        "_id" : ObjectId("61673f46b34f185eb7b2bf0f"),
        "utility" : [
                "Photography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Sifinist Croma AX",
        "price" : 99500,
        "weight" : "97 kilograms",
        "additionalDetails" : {
                "material" : "lithium",
                "moreUses" : [
                        "Videography",
                        "Water Inspection"
                ]
        }
}

You might have noticed that in the above query, we are using a ‘.’ dot which is used to access the embedded field. This is referred to as the dot notation in MongoDB. The dot notation is used when you want to access data of fields that are situated in an embedded document.

Querying Embedded Arrays Fields

Embedded array fields are the fields containing an array nested within the main document. Let’s see how to query them.

Example

Below is a query demonstrating querying a nested array field:

> db.drones.find( { "additionalDetails.moreUses" : [ "Land Inspection", "Videography" ] } ).pretty()

{
        "_id" : ObjectId("61673f46b34f185eb7b2bf10"),
        "utility" : [
                "Security",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Drovce Finnifield FR-7",
        "price" : 87600,
        "weight" : "13 kilograms",
        "additionalDetails" : {
                "material" : "polysterene",
                "moreUses" : [
                        "Land Inspection",
                        "Videography"
                ]
        }
}

Here, we again made use of the dot notation. However, to get access to the array field’s data, we passed the values into an array. This way, you may even use additional operators for querying embedded documents such as set, size, etc.

In this article, we have demonstrated only query embedded documents but you can even update embedded documents. We have an article on the findOneAndUpdate() and findAndModify() methods which can be used to select and update a single document in MongoDB, click here to read it.

Read More: Ultimate Guide to Customizing Flash Messages in Nodejs with Bootstrap

Conclusion

MongoDB is a power database having a variety of use cases such as creating schema, and APIs or using as a fully fledge database for large-scale applications. This platform provides lots of operators for accomplishing different types of operations but sometimes it becomes hard for beginners to perform operations on embedded documents, especially within a complex structure. The embedded documents are those documents that are present inside another document. 

In this article, we have seen a complete process to query embedded documents in MongoDB. The steps are not so different when compared to querying non-embedded documents. The only difference is, here we are required to use the dot notation to get to the nested field in order to specify it for querying.  After reading this article, we hope you can easily query embedded documents.

Reference

Query on Embedded/Nested Documents – MongoDB Manual

Aneesha S
Aneesha S
Articles: 171