MongoDB query to slice only one element of array


To slice only one element of array, use $slice in MongoDB. Let us create a collection with documents −

> db.demo579.insertOne(
...    {
...       "_id" : 101,
...       "details" : { "FirstName" : "John" },
...       "Marks" : [ 56,78,90,34,45,74 ]
...    }
... );
{ "acknowledged" : true, "insertedId" : 101 }

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

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

This will produce the following output −

{
   "_id" : 101,
   "details" : {
      "FirstName" : "John"
   },
   "Marks" : [
      56,
      78,
      90,
      34,
      45,
      74
   ]
}

Following is the query to slice only one the element of the array −

> db.demo579.find({},{Marks : {$slice : 1} ,"details":0,"_id":0})

This will produce the following output −

{ "Marks" : [ 56 ] }

Updated on: 15-May-2020

240 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements