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" }

Updated on: 30-Jul-2019

52 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements