Limit number of values in a field with MongoDB?


To limit the number of values in a field, use MongoDB $slice. Let us create a collection with documents −

> db.demo173.insertOne({"ListOfValues":[10,40,100,560,700,900]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e383a4f9e4f06af551997e4")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e383a4f9e4f06af551997e4"),
   "ListOfValues" : [10, 40, 100, 560, 700, 900 ]
}

Following is the query to limit number of values in a field using MongoDB −

> db.demo173.find({}, { "ListOfValues": { "$slice": -2 } } );

This will produce the following output −

{ "_id" : ObjectId("5e383a4f9e4f06af551997e4"), "ListOfValues" : [ 700, 900 ] }

Updated on: 27-Mar-2020

122 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements