Aggregate a $slice to get an element in exact position from a nested array in MongoDB?


You can use aggregate framework for this. Let us first create a collection with documents −

>db.exactPositionDemo.insertOne({"StudentName":"John","StudentScores":[78,98,56,45,89]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd29a1c345990cee87fd883")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.exactPositionDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd29a1c345990cee87fd883"),
   "StudentName" : "John",
   "StudentScores" : [
      78,
      98,
      56,
      45,
      89
   ]
}

Case 1 − Query to aggregate a $slice to get an element in exact position with 0,1 −

> db.exactPositionDemo.aggregate([ { "$project": { "StudentScores": { "$slice": ["$StudentScores",0,1] } }} ]);

This will produce the following output −

{ "_id" : ObjectId("5cd29a1c345990cee87fd883"), "StudentScores" : [ 78 ] }

Case 2 − Query to aggregate a $slice to get an element in exact position with 1,1 −

> db.exactPositionDemo.aggregate([ { "$project": { "StudentScores": { "$slice": ["$StudentScores",1,1] } }} ]);

This will produce the following output −

{ "_id" : ObjectId("5cd29a1c345990cee87fd883"), "StudentScores" : [ 98 ] }

Updated on: 30-Jul-2019

142 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements