Tutorialspoint

1 Answer
Anvi Jain

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" ] }

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.