MongoDB aggregate $slice to get the length of the array

MongoDBDatabaseBig Data Analytics

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 }
raja
Published on 02-Apr-2020 17:06:49
Advertisements