Projection of arrays to get the first array element from MongoDB documents

MongoDBDatabaseBig Data Analytics

If you want the first element from array, you can use $slice along with $gte. Let us create a collection with documents −

> db.demo640.insertOne({Name:"John","Scores":[80,90,75]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c2eb86c954c74be91e6e0")
}
> db.demo640.insertOne({Name:"Chris","Scores":[85,70,89]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c2ece6c954c74be91e6e1")
}

Display all documents from a collection with the help of find() method −

> db.demo640.find();

This will produce the following output −

{ "_id" : ObjectId("5e9c2eb86c954c74be91e6e0"), "Name" : "John", "Scores" : [ 80, 90, 75 ] }
{ "_id" : ObjectId("5e9c2ece6c954c74be91e6e1"), "Name" : "Chris", "Scores" : [ 85, 70, 89 ] }

Following is the query to projection of arrays using sing $slice −

> db.demo640.find({Scores:{$gte:85}},{ "Scores": {$slice : 1}});

This will produce the following output −

{ "_id" : ObjectId("5e9c2eb86c954c74be91e6e0"), "Name" : "John", "Scores" : [ 80 ] }
{ "_id" : ObjectId("5e9c2ece6c954c74be91e6e1"), "Name" : "Chris", "Scores" : [ 85 ] }
raja
Published on 12-May-2020 08:11:34
Advertisements