How to Query Nested Object in MongoDB
In today’s tutorial, we’ll learn how to query nested objects in MongoDB.
Query Nested Objects in MongoDB
MongoDB offers read operations to retrieve embedded or nested data from a collection or search for embedded or nested documents.
With the help of the db.collection.find()
method, we can carry out read operations. This method chooses a document from the collection embedded or nested and then returns the cursor to that document.
Syntax:
>db.collection.find($filter, $projection)
We have two options in the find()
method: $filter
and $project
, briefly described below.
-
$filter
OptionYou can use a
Document
type parameter to exclude documents. Additionally, you can use it with an empty document or without these parameters if you want to access every document in the collection. -
$project
OptionUsing this argument, we can get only particular fields that meet the supplied query filter to the documents. But, of course, you can also omit this parameter if you want to get all of the document’s fields.
This method returns a cursor to the documents that match the supplied query criteria. The find()
method returns the pointer to the documents when you use it since it returns documents when you use it.
You can read more about find()
method here. Let’s use the following example to understand the concept:
> db.users.find({address: {country: "United Kingdom"}}).pretty()
> db.users.find({address.country: "United Kingdom"}).pretty()
The sample above code used a pretty technique to locate all of the users
who are from the United Kingdom
.
The primary difference between these two approaches is that the earlier checks for addresses only include the field { country: ... }
, and the latter considers the address
.
Other fields in the address
or missing from the address
have no impact on the country
field. For example, you will see the following output after running the above code in MongoShell
.
Output:
{ "_id" : ObjectId("54f612b6029b47909a90cesd"), "email" : "johndoe@example.com", "comment" : "This is the first user in the collection.", "country" : "United Kingdom" }
Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.
LinkedIn