Ignore first 4 values in MongoDB documents and display the next 3?

MongoDBDatabaseBig Data Analytics

For this, use $slice and set thecount of values to be ignored and displayed. Let us create a collection with documents −

> db.demo693.insertOne({Values:[10,746,736,283,7363,424,3535]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea58a04ece4e5779399c07b")
}
> db.demo693.insertOne({Values:[100,200,300,100,500,700,900,30000,40003,45999]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea58a1eece4e5779399c07c")
}

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

> db.demo693.find();

This will produce the following output −

{ "_id" : ObjectId("5ea58a04ece4e5779399c07b"), "Values" : [ 10, 746, 736, 283, 7363, 424, 3535 ] }
{ "_id" : ObjectId("5ea58a1eece4e5779399c07c"), "Values" : [ 100, 200, 300, 100, 500, 700, 900, 30000, 40003, 45999 ] }

Following is the query to ignore first 4 values in MongoDB documents and display the next 3 using $slice −

> db.demo693.find({},{Values:{$slice:[4,3]}});

This will produce the following output −

{ "_id" : ObjectId("5ea58a04ece4e5779399c07b"), "Values" : [ 7363, 424, 3535 ] }
{ "_id" : ObjectId("5ea58a1eece4e5779399c07c"), "Values" : [ 500, 700, 900 ] }
raja
Published on 14-May-2020 12:45:45
Advertisements