MongoDB Limit fields and slice projection together?



Use the $slice operator. Let us first create a collection with documents −

> db.limitAndSliceProjectionDemo.insertOne(    {       "_id" : 101,       "UserName" : "Carol",       "UserAge" : 26,       "UserMesssage" : [          "Hi",          "Hello",          "Bye",          "Awesome",          "Good",          "Bad",          "Nice",          "Good Night",          "Good Morning"       ]    } ); { "acknowledged" : true, "insertedId" : 101 }

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

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

This will produce the following output −

{    "_id" : 101,    "UserName" : "Carol",    "UserAge" : 26,    "UserMesssage" : [       "Hi",       "Hello",       "Bye",       "Awesome",       "Good",       "Bad",       "Nice",       "Good Night",       "Good Morning"    ] }

Following is the query to limit fields and perform slice projection together. Here, we are slicing from 2 to 4 −

> db.limitAndSliceProjectionDemo.find({ "UserName" : "Carol" }, {"_id": 0, "UserName":0,"UserAge":0, "UserMesssage": { "$slice": [2,4] } }).pretty();

This will produce the following output −

{ "UserMesssage" : [ "Bye", "Awesome", "Good", "Bad" ] }
Updated on: 2019-07-30T22:30:26+05:30

263 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements