Mongo Query Where Object Exists in Nested Array Elementmatch
In this MongoDB tutorial, we will understandMongoDB nested question. We will cover this topic with distinct operations and examples. Additionally, we will also discuss the pursuing list of topics:
- MongoDB nested query
- MongoDB nested interrogation instance
- MongoDB query nested object not ransacked
- MongoDB nested query return specific W. C. 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 integrated or Nested document. The Embedded document or nested documents are those types of documents that curb documents inside another document.
In other Christian Bible, when a collection has a document and this document contains another document, another document contains some other sub-document, and so on, then such types of documents are better-known American Samoa embedded OR nested documents.
Notes:
- In MongoDB, you can only nest documents up to 100 levels.
- The total papers size mustiness not exceed 16 MB.
Read Create tables in MongoDB
The process of creating Enclosed documents:
In MongoDB, you posterior merely engraft a document at heart some other document. As we know that in the mongo shell, documents are defined using curly braces ( {} ) and inner these curly braces we induce field-value pairs.
Now inside these fields, we can embed or set other written document using curly braces {} and this written document may include force field-value pairs or another sub-written document.
Syntax:
{ battleground: { field1: value1, field2: value2 } }
Read How does MongoDB create collection
MongoDB nested query exercise
In that 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 assembling named 'inventory' and this collection contains the following documents.
Deep down this document, we feature a field bring up 'particular' which contains another document and this document contain two William Claude Dukenfield (i.e, sku, colourize) with their values.

The following documents wish insert into the inventory collection.
db.stock.insertMany([ { "_id" : 1, "dept" : "A", "item" : { "sku" : "101", "color" : "red" }, "sizes" : [ "S", "M" ] }, { "_id" : 2, "dept" : "A", "point" : { "sku" : "102", "color" : "dispirited" }, "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, Enclose the documents into the collection. And, check the turnout:

Thus the inventory appeal contains 4 documents and these documents contain nested documents. You can access the documents of the aggregation exploitation the find() method acting.
dubnium.inventory.find().pretty()

Show MongoDB reliever and restore
MongoDB query nested object not empty
In this MongoDB topic, you will learn to puzzle all the documents where at to the lowest degree extraordinary element of the nested set out theater is not null or empty. Let's capture understand this followed by an example.
Example:
The following documents will insert into the inventory collection.
db.take stock.insertMany( [ { item: "journal", instock: [ { storage warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] }, { item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] }, { particular: "planner", instock: [ { storage warehouse: nil, qty: 40 }, { storage warehouse: "B", qty: 5 } ] }, { item: "postcard", instock: [ { warehouse: null, qty: 15 }, { storage warehouse: null, qty: 35 } ] } ])
Let's check the execution of the code:

After that, we will hold the down the stairs query to the collection that compares all the elements of the regalia to mother all the documents where at least one element of the nested array field is non zipp Oregon void.
db.stock-taking.find( { "instock": { "$elemMatch": { "warehouse": { "$ne": null } } } } )
Here, we have ill-used the $elemMatch operator to cope with documents that contain an array battlefield 'instock' with at least one constituent that matches wholly the specific 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 induce successfully retrieved the documents where the nested raiment documents attribute is non null.
Read How to create virgin database in MongoDB
MongoDB nested query return specific fields
In this theme, you will learn to return peculiar fields from the nested documents of the MongoDB collection. Let's get sympathize this with the assistant of an example.
Illustration:
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" : { "tup" : 4, "block out" : 6.5, "cpu" : 2.66 }, "coloration" : [ "white", "black" ], "storage" : [ 64, 128, 256 ] }, { "_id" : 2, "describ" : "xTablet", "price" : 899, "releaseDate" : ISODate("2011-09-01T00:00:00Z"), "spec" : { "ram" : 16, "screen" : 9.5, "central processing unit" : 3.66 }, "color" : [ "white", "fatal", "purple" ], "storage" : [ 128, 256, 512 ] }, { "_id" : 3, "name" : "SmartTablet", "price" : 899, "releaseDate" : ISODate("2015-01-14T00:00:00Z"), "spec" : { "ram" : 12, "screen" : 9.7, "central processing unit" : 3.66 }, "emblazon" : [ "blue" ], "computer memory" : [ 16, 64, 128 ] }, { "_id" : 4, "name" : "SmartPad", "monetary value" : 699, "releaseDate" : ISODate("2020-05-14T00:00:00Z"), "spec" : { "ram" : 8, "screen" : 9.7, "cpu" : 1.66 }, "color" : [ "white", "orange", "golden", "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 tree", "gilt", "gray" ], "storage" : [ 128, 256 ] } ])
After that, we will lend oneself the following query to find to return specific fields from the nested documents.
db.products.rule( {"spec.ram": { $gt: 4} })
Here, we have utilised the $gt greater than operator to turn back the limited 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 Simon Marks.

We have successfully returned the nested lay out specific documents of the solicitation.
Read Export MongoDB to CSV
MongoDB nested query array
In this topic, you will learn to find the MongoDB collection nested regalia matches specified document. So let's get understand this followed away an example.
Example:
In this example, we will learn to line up out those documents match from the nested array field.
The following documents were inserted into the inventory collection.
atomic number 105.inventory.insertMany([ { "item": "journal", "instock": [ { "warehouse": "A", "qty": 5 }, { "storage warehouse": "C", "qty": 15 } ] }, { "item": "notebook", "instock": [ { "warehouse": "C", "qty": 5 } ] }, { "item": "contriver", "instock": [ { "warehouse": null, "qty": 40 }, { "warehouse": "B", "qty": 5 } ] }, { "item": "mailing-card", "instock": [ { "warehouse": null, "qty": 15 }, { "warehouse": null, "qty": 35 } ] } ])
After that, we bequeath apply the pursual inquiry to return selected all documents where an element in the instock regalia matches the specified text file.
db.inventory.find( { "instock": { warehouse: "A", qty: 5 } } )
Promissory note that, equality matches all in all embedded or nested document require anexact match of the specified document, including the area order.
For example, the subsequent query does not peer any documents in the inventory collection:
element 105.inventory.determine( { "instock": { qty: 5, warehouse: "A" } } )
Let's check the production now;

We have got successfully retrieved the nested array text file of the collecting.
Read MongoDB is not recognized equally an internal operating room external dominate
MongoDB nested query not equal
In this topic, you leave learn to find all the documents in MongoDB that are in the nested array form where the value of the field is not adequate to the specified valuate.
MongoDB provides the $ne that selects the documents where the value of the field is not equalize to the defined value. This covers documents that do non curb the field.
Syntax:
{ field: { $ne: value } }
Let's get understand this topic followed aside an lesson.
Lesson:
The following documents were inserted into the stock-take collection.
db.take stock.insertMany([ { "_id" : 1, "dept" : "A", "particular" : { "sku" : "101", "people of colour" : "red" }, "sizes" : [ "S", "M" ] }, { "_id" : 2, "dept" : "A", "item" : { "sku" : "102", "coloration" : "risque" }, "sizes" : [ "M", "L" ] }, { "_id" : 3, "dept" : "B", "item" : { "sku" : "103", "color" : "blue" }, "sizes" : "S" }, { "_id" : 4, "dept" : "A", "point" : { "sku" : "104", "color" : "black" }, "sizes" : [ "S" ] } ])
Now, we will apply the following inquiry to select all documents from the stock-taking aggregation where the nested array field value does not equal.
decibel.stock-take.find({ "item.color": { $ne: "blue"} })
Present, we have used the $nor'-east operation and applied query on nested array field 'item.people of color' to return documents where 'color' is non equal to 'blueish'.
Check the output at once;

We have successfully launch all the documents where the nested array field is non equal.
Read MongoDB link up two collections
MongoDB nested query match
In this topic, you will instruct to find those documents from the MongoDB collecting 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 regalia field.
The following documents were inserted into the inventory aggregation.
db.inventory.insertMany( [ { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, position: "A" }, { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" }, { detail: "composition", qty: 100, sizing: { h: 8.5, w: 11, uom: "in" }, position: "D" }, { item: "planner", qty: 75, size up: { h: 22.85, w: 30, uom: "Cm" }, position: "D" }, { item: "postcard", qty: 45, size up: { h: 10, w: 15.25, uom: "atomic number 96" }, status: "A" } ])
Now, we will apply the following query to couple the nested array field and pick up those documents that satisfy the condition.
hahnium.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )
Billet that, equality matches all in all embedded or nested papers require anverbatim match of the specified written document, including the field order.
For example, the subsequent query does non match whatsoever documents in the inventory collection:
db.take stock.find( { size: { w: 21, h: 14, uom: "cm" } } )
Let's audit the end product now;

We have successfully retrieved the matched nested raiment documents of the MongoDB solicitation.
Also read, Importee CSV into MongoDB
MongoDB nested enquiry using python
In MongoDB, queries work 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 diligence.
In this topic, we will learn to come up the MongoDB documents that are in the nested set out form with the help of Python. Let's get understand this with help of an example.
Example:
In the write in code, we have imported the pymongo depository library to interact 'tween the mongo database and Python application. After that, conform to the below steps;
- Create MongoClient object and connect with the host.
- Later that access that active database and solicitation of MongoDB, mydatabase and inventory respectively.
- Close, enjoyment the line up() method to reterive list of all the documents as per specify term.
- Here, The condition is find douments where nested array field 'size.h' is equal to 14.
import pymongo # creating a MongoClient targe and connect with the host myclient = pymongo.MongoClient("mongodb://127.0.0.1:27017") # accessing the database mydb = myclient["mydatabase"] # accessing the assemblage of the database mycol = mydb["inventory"] # return the nested align documents collect = mycol.see({ "size of it.h": 14 }) for nested_documents in collect: print(nested_documents)
Have's check the output signal now;

We have with success retrieved the nested regalia 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 escort
- MongoDB sort by field
- MongoDB group aside multiple W. C. Fields
Soh, In this tutorial, we have taken aboutMongoDB nested query. And, we have covered the different operations with examples. We have thickspread the following name of topics:
- MongoDB nested query
- MongoDB nested query example
- MongoDB interrogation nested object not empty
- MongoDB nested interrogation return specific Fields
- MongoDB nested query array
- MongoDB nested query non equal
- MongoDB nested query match
- MongoDB nested query using python
Bijay is a Microsoft MVP since 2014 (7 times+) specialized in SharePoint. Helium is having much 14 years of experience in SharePoint (Most Favourite Content Management System in The United States of America (USA)) and different Microsoft technologies. Bijay is an enterpriser, a technical blogger, and passionate roughly driving, wrote dozens of articles in his personal blogs EnjoySharePoint.com and SPGuides.com, and PythonGuides.com focuses on speaking activities for diverse exploiter groups. Atomic number 2 is the co-fall flat of TSInfo Technologies, a SharePoint Consulting, Outsourcing, Development, and training company.
During the longish 14+ years of my business career, I have used SQL Server in lots of projects. Enjoy my SQL Server tutorials.
Mongo Query Where Object Exists in Nested Array Elementmatch
Source: https://sqlserverguides.com/mongodb-nested-query/
0 Response to "Mongo Query Where Object Exists in Nested Array Elementmatch"
Post a Comment