0% found this document useful (0 votes)
5 views21 pages

Querying Embedded Documents

The document explains how to query embedded/nested documents in MongoDB using the db.collection.find() method, including syntax, parameters, and examples. It covers matching conditions, using dot notation for nested fields, and applying query operators for more complex queries. Additionally, it provides examples of inserting, retrieving, and updating embedded documents within collections.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views21 pages

Querying Embedded Documents

The document explains how to query embedded/nested documents in MongoDB using the db.collection.find() method, including syntax, parameters, and examples. It covers matching conditions, using dot notation for nested fields, and applying query operators for more complex queries. Additionally, it provides examples of inserting, retrieving, and updating embedded documents within collections.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Querying Embedded Documents

MongoDB provides you read operations to retrieve embedded/nested documents from the
collection or query a collection for a embedded/nested document. You can perform read
operations using the db.collection.find() method. This method selects or views
embedded/nested documents of the collection and returns the cursor to the selected document.
Syntax: db.collection.find(filter, projection)
Parameters:
 filter: It is an optional parameter. It specifies the selection filter with the help of query
operators. And if you want to get all the documents present in the collection, then omit
these parameters or pass an empty document in the method. The type of this parameter is a
Document.
 projection: It is an optional parameter. It specifies that only those fields return to the
document that matches the given query filter. And if you want to get all the fields in the
document, then omit this parameter. Learn more.
Return: This method returns a cursor to the documents that match the specified query criteria.
When you use find() method, it returns documents, which means the method is actually
returning the cursor to the documents.

This page provides examples of query operations on embedded/nested documents using


the db.collection.find() method in the mongo shell. The examples on this page use
the inventory collection. To populate the inventory collection, run the following:

Example 1:

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" }

]);
Match an Embedded/Nested Document

To specify an equality condition on a field that is an embedded/nested document, use the query
filter document { <field>: <value> } where <value> is the document to match.

For example, the following query selects all documents where the field size equals the
document { h: 14, w: 21, uom: "cm" }:

db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )


Query on Nested Field

To specify a query condition on fields in an embedded/nested document, use dot


notation ("field.nestedField").

NOTE

When querying using dot notation, the field and nested field must be inside quotation marks.

Specify Equality Match on a Nested Field

The following example selects all documents where the field uom nested in the size field
equals "in":

db.inventory.find( { "size.uom": "in" } )

db.inventory.find( { "size.w": 11 } ).pretty()


Specify Match using Query Operator

A query filter document can use the query operators to specify conditions in the following form:

{ <field1>: { <operator1>: <value1> }, ... }

The following query uses the less than operator ($lt) on the field h embedded in the size field:

db.inventory.find( { "size.h": { $lt: 10 } } )


Specify AND Condition

The following query selects all documents where the nested field h is less than 15, the nested
field uom equals "in", and the status field equals "D":

db.inventory.find( { "size.h": { $lt: 15 }, "size.uom": "in", status: "D" } ).pretty()


Example 2:
Accessing embedded/nested documents –
In MongoDB, you can access the fields of nested/embedded documents of the collection using
dot notation and when you are using dot notation, then the field and the nested field must be
inside the quotation marks.
Syntax:
"field.nestedField": value
In the following examples, we are working with:
Database: GeeksforGeeks
Collection: Courses
Document: three documents that contain the details of the students in the form of field-value
pairs.
Matching embedded/nested document –
In this example, we are retrieving the documents that exactly match the given embedded
document.

db.Courses.find({name: {first: "Rohit",

middle: "Kumar",

last: "Singh"}}).pretty()

Output:

Select documents that match the nested field –


In this example, we are retrieving the documents that match the specified nested field.

db.Courses.find({"courseDetails.name": "Java Backend Development"}).pretty()


Output :

Select documents that match the nested field (Using query operators) –
In this example, we are retrieving the documents that match the nested field using the query
operators. Here, in the query, we use $in operator. This operator is used to match any of the
values specified in the given array.

db.Courses.find({"name.first": {$in: ["Rohit", "Mohit"]}}).pretty()

Output:

Select documents that match the nested fields (Using AND condition) –
In this example, we are retrieving the documents that match the nested fields.

db.Courses.find({"courseDetails.name": "Sudo GATE 2020",

"name.first": "Mohit"}).pretty()

Output:

Getting the specified fields from the embedded/nested documents :


In this example, we are retrieving fields from the embedded/nested documents using
projection.

db.Courses.find({branch: "CSE"}, {"name.first": 1,

"name.last": 1}).pretty()
Example 3:

Run the following command to insert some documents in the shapes collection.

> db.shapes.insertMany([

"shape": "rectangle",

"item": "Rect 1",

"dim": {

"length": 10,

"breadth": 20,

"uom": "cm"

},
{

"shape": "rectangle",

"item": "Rect 2",

"dim": {

"length": 20,

"breadth": 30,

"uom": "cm"

},

"shape": "rectangle",

"item": "Rect 3",

"dim": {

"length": 5,

"breadth": 10,

"uom": "cm"

},

"shape": "square",

"item": "Sq 1",

"dim": {
"side": 10.5,

"uom": "cm"

},

"shape": "square",

"item": "Sq 2",

"dim": {

"side": 20,

"uom": "cm"

},

"shape": "square",

"item": "Sq 3",

"dim": {

"side": 15,

"uom": "inch"

},

"shape": "square",
"item": "Sq 4",

"dim": {

"side": 25.5,

"uom": "inch"

]);

We learned how to create embedded documents in the Insert Document tutorial. Feel free to
check that out.

Alright, let's start simple then progress to advance problems.

Find all rectangles

To find all the documents in the shapes collection that represents a rectangle we have to run the
following command.

> db.shapes.find({ "shape": "rectangle" }).pretty();

"_id" : ObjectId("5d175dffba3250e57f98faca"),

"shape" : "rectangle",

"item" : "Rect 1",

"dim" : {

"length" : 10,

"breadth" : 20,
"uom" : "cm"

"_id" : ObjectId("5d175dffba3250e57f98facb"),

"shape" : "rectangle",

"item" : "Rect 2",

"dim" : {

"length" : 20,

"breadth" : 30,

"uom" : "cm"

"_id" : ObjectId("5d175dffba3250e57f98facc"),

"shape" : "rectangle",

"item" : "Rect 3",

"dim" : {

"length" : 5,

"breadth" : 10,

"uom" : "cm"

}
}

Find squares with sides at least 20 cm

Alright, we are now moving to embedded documents.

First we have to check the shape to be equal to square.

Next, we have to check the side field which is inside the dim field. So, we have to
use dim.side in our filter.

We have to make sure the side is at least 20 cm so, we have to use the $gte greater than or equal
to operator for the dim.side field.

And for the unit of measurement uom we have to check the dim.uom to be equal to cm.

Our query should look like the following.

> db.shapes.find({

"shape": "square",

"dim.side": { $gte: 20 },

"dim.uom": "cm"

}).pretty();

"_id" : ObjectId("5d175dffba3250e57f98face"),

"shape" : "square",

"item" : "Sq 2",

"dim" : {

"side" : 20,
"uom" : "cm"

Find all rectangles having length at least 10 cm and breadth at least 20 cm

For this we have to check the following.

 shape is rectangle
 dim.length is at least (i.e. greater than or equal to) 10
 dim.breadth is at least (i.e. greater than or equal to) 20
 dim.uom is cm

> db.shapes.find({

"shape": "rectangle",

"dim.length": { $gte: 10 },

"dim.breadth": { $gte: 20 },

"dim.uom": "cm"

}).pretty();

"_id" : ObjectId("5d175dffba3250e57f98faca"),

"shape" : "rectangle",

"item" : "Rect 1",

"dim" : {

"length" : 10,
"breadth" : 20,

"uom" : "cm"

"_id" : ObjectId("5d175dffba3250e57f98facb"),

"shape" : "rectangle",

"item" : "Rect 2",

"dim" : {

"length" : 20,

"breadth" : 30,

"uom" : "cm"

Updating Nested Embedded Documents in MongoDB

To update bested documents in MongDB, use UPDATE() and positional($) operator. Let us
create a collection with documents −

> db.demo643.insertOne({

... details : [

... {

... "CountryName":"US",
... StudentDetails:[{Name:"Chris"},{SubjectName:"MySQL"}]

... },

...

... {

... "CountryName":"UK",

... StudentDetails:[{Name:"Bob"},{SubjectName:"Java"}]

... }

... ]

... }

... )

"acknowledged" : true,

"insertedId" : ObjectId("5e9c737f6c954c74be91e6e3")

Display all documents from a collection with the help of find() method −

> db.demo643.find();

This will produce the following output −

{ "_id" : ObjectId("5e9c737f6c954c74be91e6e3"), "details" : [ { "CountryName" : "US",


"StudentDetails" : [ { "Name" : "Chris" }, { "SubjectName" : "MySQL" } ] }, { "CountryName"
: "UK", "StudentDetails" : [ { "Name" : "Bob" }, { "SubjectName" : "Java" } ] } ] }

Following is the query to update nested embedded documents in MongoDB −

> db.demo643.update({"details.CountryName": "UK"}, {"$push": {"details.$.StudentDetails":


{Marks:78}}})

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Display all documents from a collection with the help of find() method −

> db.demo643.find().pretty();
This will produce the following output −

{
"_id" : ObjectId("5e9c737f6c954c74be91e6e3"),
"details" : [
{
"CountryName" : "US",
"StudentDetails" : [
{
"Name" : "Chris"
},
{
"SubjectName" : "MySQL"
}
]
},
{
"CountryName" : "UK",
"StudentDetails" : [
{
"Name" : "Bob"
},
{
"SubjectName" : "Java"
},
{
"Marks" : 78
}
]
}
]
}

You might also like