- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 Aggregation to slice array inside array
For this, use aggregate() in MongoDB. In that, use $slice to slice array inside array. Let us create a collection with documents −
> db.demo111.insertOne( ... { ... "_id" : 101, ... "Name" : "Chris", ... "Details" : [ ... { ... "_id" : 101, ... "Score" : 78, ... "Subjects" : [ ... { ... "_id" : "10001", ... "SubjectName" : "MySQL" ... }, ... { ... "_id" : "10003", ... "SubjectName" : "MongoDB" ... } ... ] ... }, ... { ... "_id" : 102, ... "Score" : 87, ... "Subjects" : [ ... { ... "_id" : "10004", ... "SubjectName" : "Java" ... } ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 101 }
Display all documents from a collection with the help of find() method −
> db.demo111.find();
This will produce the following output −
{ "_id" : 101, "Name" : "Chris", "Details" : [ { "_id" : 101, "Score" : 78, "Subjects" : [ { "_id" : "10001", "SubjectName" : "MySQL" }, { "_id" : "10003", "SubjectName" : "MongoDB" } ] }, { "_id" : 102, "Score" : 87, "Subjects" : [ { "_id" : "10004", "SubjectName" : "Java" } ] } ] }
Following is the query to slice array inside array −
> db.demo111.aggregate([ ... { "$addFields": { ... "Details": { ... "$map": { ... "input": "$Details", ... "as": "out", ... "in": { ... "_id": "$$out._id", ... "Score": "$$out.Score", ... "Subjects": { "$slice": [ "$$out.Subjects", 1 ] } ... } ... } ... } ... }} ... ])
This will produce the following output −
{ "_id" : 101, "Name" : "Chris", "Details" : [ { "_id" : 101, "Score" : 78, "Subjects" : [ { "_id" : "10001", "SubjectName" : "MySQL" } ] }, { "_id" : 102, "Score" : 87, "Subjects" : [ { "_id" : "10004", "SubjectName" : "Java" } ] } ] }
Advertisements