MongoDB aggregate $slice to get the length of the array


For this, use $project and in that, $size to get the length. Let us first create a collection with documents −

> db.demo382.insertOne(
...    {
...
...       "Name" : "David",
...       "details" : [
...          {
...             "SubjectName":"MySQL"
...          },
...          {
...             "SubjectName":"MongoDB"
...          },
...          {
...             "SubjectName":"Java"
...          }
...       ]
...
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5b5e1c22064be7ab44e7f0")
}

Display all documents from a collection with the help of find() method &Minus;

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

This will produce the following output −

{
   "_id" : ObjectId("5e5b5e1c22064be7ab44e7f0"),
   "Name" : "David",
   "details" : [
      {
         "SubjectName" : "MySQL"
      },
      {
         "SubjectName" : "MongoDB"
      },
      {
         "SubjectName" : "Java"
      }
   ]
}

Following is the query to aggregate $slice and get the length −

> db.demo382.aggregate([
...    { "$match": { "Name": "David" } },
...    { "$project": { "count": { "$size": "$details" }}}
... ])

This will produce the following output −

{ "_id" : ObjectId("5e5b5e1c22064be7ab44e7f0"), "count" : 3 }

Updated on: 02-Apr-2020

332 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements