Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Filter query on array of embedded document with MongoDB?
For this, use aggregate() in MongoDB. Let us create a collection with documents −
> db.demo736.insertOne(
... {
... "_id": "101",
... "details1": [
... {
... "details2": [
... {
... "details3": {
... "Name": "John"
... }
... }
... ]
... }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : "101" }
> db.demo736.insertOne(
... {
... "_id": "102",
... "details1": [
... {
... "details2": [
... {
... "details3": {
... "Name": "Robert"
... }
... }
... ]
... }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : "102" }
Display all documents from a collection with the help of find() method −
> db.demo736.find();
This will produce the following output −
{ "_id" : "101", "details1" : [ { "details2" : [ { "details3" : { "Name" : "John" } } ] } ] }
{ "_id" : "102", "details1" : [ { "details2" : [ { "details3" : { "Name" : "Robert" } } ] } ] }
Following is the query to filter array of embedded documents (3 levels) in MongoDB −
> db.demo736.aggregate([
... {
... "$unwind": "$details1"
... },
... {
... "$unwind": "$details1.details2"
... },
... {
... "$match": {
... "details1.details2.details3.Name": "Robert"
... }
... },
... {
... $project: {
... _id: 0,
... Name: "$details1.details2.details3",
... }
... }
... ])
This will produce the following output −
{ "Name" : { "Name" : "Robert" } }Advertisements