How do you limit an array sub-element in MongoDB?


You can use $slice operator to limit an array. Let us create a collection with documents. Following is the query

> db.limitAnArrayDemo.insertOne(
...    {
...       _id: 101,
...       "PlayerName": "Bob",
...       "PlayerDetails": {Age:23,isStudent:true},
...       "PlayerGameScores": [234,5767,58,67,78,90,1002,576,68,45,23,45,678,89,78 ]
...    }
... );
{ "acknowledged" : true, "insertedId" : 101 }

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

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

This will produce the following output

{
   "_id" : 101,
   "PlayerName" : "Bob",
   "PlayerDetails" : {
      "Age" : 23,
      "isStudent" : true
   },
   "PlayerGameScores" : [
      234,
      5767,
      58,
      67,
      78,
      90,
      1002,
      576,
      68,
      45,
      23,
      45,
      678,
      89,
      78
   ]
}

Following is the query to limit an array sub-element in MongoDB. The below query will display only 10 elements from the last

> db.limitAnArrayDemo.find({}, {PlayerName:1, PlayerDetails: 1, PlayerGameScores:{$slice: -10}}).pretty();

Following is the output displaying 10 PlayerGameScores

{
   "_id" : 101,
   "PlayerName" : "Bob",
   "PlayerDetails" : {
      "Age" : 23,
      "isStudent" : true
   },
   "PlayerGameScores" : [
      90,
      1002,
      576,
      68,
      45,
      23,
      45,
      678,
      89,
      78
   ]
}

Updated on: 30-Jul-2019

625 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements