In this MongoDB tutorial, we will understand MongoDB nested query. We will cover this topic with different operations and examples. Additionally, we will also discuss the following list of topics:
- MongoDB nested query
- MongoDB nested query example
- MongoDB query nested object not empty
- MongoDB nested query return specific fields
- MongoDB nested query array
- MongoDB nested query not equal
- MongoDB nested query match
- MongoDB nested query using python
MongoDB nested query
MongoDB provides a feature which is known as embedded or Nested document. The Embedded document or nested documents are those types of documents that contain documents inside another document.
In another word, when a collection has a document and this document contains another document, another document contains another sub-document, and so on, then such types of documents are known as embedded or nested documents.
Notes:
- In MongoDB, you can only nest documents up to 100 levels.
- The total document size must not exceed 16 MB.
The process of creating Embedded documents:
In MongoDB, you can simply embed a document inside another document. As we know that in the mongo shell, documents are defined using curly braces ( {} ) and inside these curly braces we have field-value pairs.
Now inside these fields, we can embed or set another document using curly braces {} and this document may include field-value pairs or another sub-document.
Syntax:
{
field: { field1: value1, field2: value2 }
}
Read How does MongoDB create collection
MongoDB nested query example
In this MongoDB topic, you will understand the nested query concept with the help of the given example.
Example:
We have a database ‘Company’. Now this database has a collection named ‘inventory’ and this collection contains the following documents.
Inside this document, we have a field name ‘item’ which contains another document and this document contain two fields (i.e, sku, color) with their values.

The following documents will insert into the inventory collection.
db.inventory.insertMany([
{ "_id" : 1, "dept" : "A", "item" : { "sku" : "101", "color" : "red" }, "sizes" : [ "S", "M" ] },
{ "_id" : 2, "dept" : "A", "item" : { "sku" : "102", "color" : "blue" }, "sizes" : [ "M", "L" ] },
{ "_id" : 3, "dept" : "B", "item" : { "sku" : "103", "color" : "blue" }, "sizes" : "S" },
{ "_id" : 4, "dept" : "A", "item" : { "sku" : "104", "color" : "black" }, "sizes" : [ "S" ] }
])
Now, Insert the documents into the collection. And, check the output:

So the inventory collection contains 4 documents and these documents contain nested documents. You can access the documents of the collection using the find() method.
db.inventory.find().pretty()

Read MongoDB backup and restore
MongoDB query nested object not empty
In this MongoDB topic, you will learn to get all the documents where at least one element of the nested array field is not null or empty. Let’s get understand this followed by an example.
Example:
The following documents will insert into the inventory collection.
db.inventory.insertMany( [
{ item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
{ item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
{ item: "planner", instock: [ { warehouse: null, qty: 40 }, { warehouse: "B", qty: 5 } ] },
{ item: "postcard", instock: [ { warehouse: null, qty: 15 }, { warehouse: null, qty: 35 } ] }
])
Let’s check the execution of the code:

After that, we will apply the below query to the collection that compares all the elements of the array to get all the documents where at least one element of the nested array field is not null or empty.
db.inventory.find(
{
"instock":
{
"$elemMatch":
{ "warehouse":
{ "$ne": null }
}
}
}
)
Here, we have used the $elemMatch operator to match documents that contain an array field ‘instock’ with at least one element that matches all the specified query criteria.
And, the $ne is used to select the documents where the value of the field ‘warehouse’ is not equal to the specified value.

We have successfully retrieved the documents where the nested array documents property is not null.
Read How to create new database in MongoDB
MongoDB nested query return specific fields
In this topic, you will learn to return specific fields from the nested documents of the MongoDB collection. Let’s get understand this with the help of an example.
Example:
The following documents were inserted into the products collection.
db.products.insertMany([
{ "_id" : 1, "name" : "xPhone", "price" : 799, "releaseDate" : ISODate("2011-05-14T00:00:00Z"), "spec" : { "ram" : 4, "screen" : 6.5, "cpu" : 2.66 }, "color" : [ "white", "black" ], "storage" : [ 64, 128, 256 ] },
{ "_id" : 2, "name" : "xTablet", "price" : 899, "releaseDate" : ISODate("2011-09-01T00:00:00Z"), "spec" : { "ram" : 16, "screen" : 9.5, "cpu" : 3.66 }, "color" : [ "white", "black", "purple" ], "storage" : [ 128, 256, 512 ] },
{ "_id" : 3, "name" : "SmartTablet", "price" : 899, "releaseDate" : ISODate("2015-01-14T00:00:00Z"), "spec" : { "ram" : 12, "screen" : 9.7, "cpu" : 3.66 }, "color" : [ "blue" ], "storage" : [ 16, 64, 128 ] },
{ "_id" : 4, "name" : "SmartPad", "price" : 699, "releaseDate" : ISODate("2020-05-14T00:00:00Z"), "spec" : { "ram" : 8, "screen" : 9.7, "cpu" : 1.66 }, "color" : [ "white", "orange", "gold", "gray" ], "storage" : [ 128, 256, 1024 ] },
{ "_id" : 5, "name" : "SmartPhone", "price" : 599, "releaseDate" : ISODate("2022-09-14T00:00:00Z"), "spec" : { "ram" : 4, "screen" : 5.7, "cpu" : 1.66 }, "color" : [ "white", "orange", "gold", "gray" ], "storage" : [ 128, 256 ] }
])
After that, we will apply the following query to find to return specific fields from the nested documents.
db.products.find( {"spec.ram": { $gt: 4} })
Here, we have used the $gt greater than operator to return the specific documents where the ‘spec.ram’ is greater than 4.
Note that, When accessing the documents using dot notation, the field and nested field must be inside quotation marks.

We have successfully returned the nested array specific documents of the collection.
MongoDB nested query array
In this topic, you will learn to find the MongoDB collection nested array matches specified document. So let’s get understand this followed by an example.
Example:
In this example, we will learn to find out those documents match from the nested array field.
The following documents were inserted into the inventory collection.
db.inventory.insertMany([
{ "item": "journal", "instock": [ { "warehouse": "A", "qty": 5 }, { "warehouse": "C", "qty": 15 } ] },
{ "item": "notebook", "instock": [ { "warehouse": "C", "qty": 5 } ] },
{ "item": "planner", "instock": [ { "warehouse": null, "qty": 40 }, { "warehouse": "B", "qty": 5 } ] },
{ "item": "postcard", "instock": [ { "warehouse": null, "qty": 15 }, { "warehouse": null, "qty": 35 } ] }
])
After that, we will apply the following query to return selected all documents where an element in the instock array matches the specified document.
db.inventory.find( { "instock": { warehouse: "A", qty: 5 } } )
Note that, equality matches on the whole embedded or nested document require an exact match of the specified document, including the field order.
For example, the subsequent query does not match any documents in the inventory collection:
db.inventory.find( { "instock": { qty: 5, warehouse: "A" } } )
Let’s check the output now;

We have successfully retrieved the nested array document of the collection.
Read MongoDB is not recognized as an internal or external command
MongoDB nested query not equal
In this topic, you will learn to find all the documents in MongoDB that are in the nested array form where the value of the field is not equal to the specified value.
MongoDB provides the $ne that selects the documents where the value of the field is not equal to the defined value. This covers documents that do not contain the field.
Syntax:
{ field: { $ne: value } }
Let’s get understand this topic followed by an example.
Example:
The following documents were inserted into the inventory collection.
db.inventory.insertMany([
{ "_id" : 1, "dept" : "A", "item" : { "sku" : "101", "color" : "red" }, "sizes" : [ "S", "M" ] },
{ "_id" : 2, "dept" : "A", "item" : { "sku" : "102", "color" : "blue" }, "sizes" : [ "M", "L" ] },
{ "_id" : 3, "dept" : "B", "item" : { "sku" : "103", "color" : "blue" }, "sizes" : "S" },
{ "_id" : 4, "dept" : "A", "item" : { "sku" : "104", "color" : "black" }, "sizes" : [ "S" ] }
])
Now, we will apply the following query to select all documents from the inventory collection where the nested array field value does not equal.
db.inventory.find({ "item.color": { $ne: "blue"} })
Here, we have used the $ne operation and applied query on nested array field ‘item.color’ to return documents where ‘color’ is not equal to ‘blue’.
Check the output now;

We have successfully found all the documents where the nested array field is not equal.
Read MongoDB join two collections
MongoDB nested query match
In this topic, you will learn to find those documents from the MongoDB collection that match the nested array field. Let’s understand this with the help of an example.
Example:
In this example, we will find out those documents from the MongoDB collection that match the nested array field.
The following documents were inserted into the inventory collection.
db.inventory.insertMany( [
{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
])
Now, we will apply the following query to match the nested array field and find out those documents that satisfy the condition.
db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )
Note that, equality matches on the whole embedded or nested document require an exact match of the specified document, including the field order.
For example, the subsequent query does not match any documents in the inventory collection:
db.inventory.find( { size: { w: 21, h: 14, uom: "cm" } } )
Let’s inspect the output now;

We have successfully retrieved the matched nested array documents of the MongoDB collection.
Also read, Import CSV into MongoDB
MongoDB nested query using python
In MongoDB, queries play an important role to fetch a particular record from the MongoD document. The pymongo is a python module that is used to interact between the mongo database and Python application.
In this topic, we will learn to find the MongoDB documents that are in the nested array form with the help of python. Let’s get understand this with help of an example.
Example:
In the code, we have imported the pymongo library to interact between the mongo database and Python application. After that, follow the below steps;
- Create MongoClient object and connect with the host.
- After that access that existing database and collection of MongoDB, mydatabase and inventory respectively.
- Next, use the find() method to reterive list of all the documents as per define condition.
- Here, The condition is find douments where nested array field ‘size.h’ is equal to 14.
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["mydatabase"]
# accessing the collection of the database
mycol = mydb["inventory"]
# return the nested array documents
collect = mycol.find({ "size.h": 14 })
for nested_documents in collect:
print(nested_documents)
Let’s check the output now;

We have successfully retrieved the nested array documents of the MongoDB collection using python.
Related MongoDB tutorials:
- MongoDB shutting down with code 100
- How to check if MongoDB is installed
- MongoDB sort by date
- MongoDB sort by field
- MongoDB group by multiple fields
So, In this tutorial, we have understood about MongoDB nested query. And, we have covered the different operations with examples. We have covered the following list of topics:
- MongoDB nested query
- MongoDB nested query example
- MongoDB query nested object not empty
- MongoDB nested query return specific fields
- MongoDB nested query array
- MongoDB nested query not equal
- MongoDB nested query match
- MongoDB nested query using python
I am Bijay having more than 15 years of experience in the Software Industry. During this time, I have worked on MariaDB and used it in a lot of projects. Most of our readers are from the United States, Canada, United Kingdom, Australia, New Zealand, etc.
Want to learn MariaDB? Check out all the articles and tutorials that I wrote on MariaDB. Also, I am a Microsoft MVP.