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
MongoDB projection on specific nested properties?
For projection on specific nested properties, use aggregate() in MongoDB. Let us first create a collection with documents −
> db.demo379.insertOne(
... {
... "details1" : {
... "details2" : {
... "details3" : {
... "10" : "John",
... "50" : "Chris",
... "40" : "David",
... "30":"Mike"
... }
... }
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e5a94f82ae06a1609a00b10")
}
Display all documents from a collection with the help of find() method −
> db.demo379.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5e5a94f82ae06a1609a00b10"),
"details1" : {
"details2" : {
"details3" : {
"10" : "John",
"30" : "Mike",
"40" : "David",
"50" : "Chris"
}
}
}
}
Following is the query for projection on specific nested properties −
> db.demo379.aggregate([
... { "$addFields": {
... "details1.details2.details3": {
... "$arrayToObject": {
... "$filter": {
... "input": { "$objectToArray": "$details1.details2.details3" },
... "as": "out",
... "cond": {
... "$and": [
... { "$gte": ["$$out.k", "35"] },
... { "$lte": ["$$out.k", "60"] },
... ]
... }
... }
... }
... }
... } }
... ])
This will produce the following output −
{ "_id" : ObjectId("5e5a94f82ae06a1609a00b10"), "details1" : { "details2" : { "details3" : { "40" : "David", "50" : "Chris" } } } }Advertisements