- 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
Is it possible to achieve a slice chain in MongoDB?
Yes, you can achieve this using aggregate framework. Let us first create a collection with documents −
> db.sliceOfSliceDemo.insertOne( ... { ... "Name": "John", ... "Details": [["First 1:1", "First 1:2"],["second 2:1","Second 2:2"]] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5ccf3fcfdceb9a92e6aa195a") }
Following is the query to display all documents from a collection with the help of find() method −
> db.sliceOfSliceDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5ccf3fcfdceb9a92e6aa195a"), "Name" : "John", "Details" : [ [ "First 1:1", "First 1:2" ], [ "second 2:1", "Second 2:2" ] ] }
Following is the query to get a slice of a slice i.e. achieve a slice chain in MongoDB −
> db.sliceOfSliceDemo.aggregate([ {$match:{"Name":"John"}}, {$unwind:"$Details"}, {$unwind:"$Details"}, {$group:{"_id":"$Name","Details":{$last:"$Details"}}}, {$project:{"Name":"$_id","Details":1}} ]);
This will produce the following output −
{ "_id" : "John", "Details" : "Second 2:2", "Name" : "John" }
Advertisements