Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Querying on an array of objects for specific nested documents with MongoDB?
To query on an array of objects for nested documents, use find(). Let us create a collection with documents −
> db.demo763.insertOne(
... {
... _id:1,
... CountryName:"US",
... "studentInformation": [
... {
... StudentName:"Chris",
... },
... {
... StudentName:"David",
... StudentAge:22
... }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : 1 }
Display all documents from a collection with the help of find() method −
> db.demo763.find();
This will produce the following output −
{ "_id" : 1, "CountryName" : "US", "studentInformation" : [ { "StudentName" : "Chris" }, { "StudentName" : "David", "StudentAge" : 22 } ] }
Following is how to query an array of objects to fetch specific nested documents −
> db.demo763.find({},
... {
... studentInformation: {
... $elemMatch: {
... StudentAge: {
... $exists: true
... }
... }
... }
... })
This will produce the following output −
{ "_id" : 1, "studentInformation" : [ { "StudentName" : "David", "StudentAge" : 22 } ] } Advertisements
