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

MongoDBDatabaseBig Data Analytics

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 ] }
raja
Published on 22-May-2019 09:26:16
Advertisements