Is it possible to achieve a slice chain in MongoDB?

MongoDBDatabaseBig Data Analytics

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" }
raja
Published on 22-May-2019 07:53:00
Advertisements