MongoDB Aggregation to slice array inside array

MongoDBDatabaseBig Data Analytics

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" } ] }
   ] 
}
raja
Published on 30-Mar-2020 15:26:39
Advertisements