MongoDB query to count the size of an array distinctly?

MongoDBDatabaseBig Data Analytics

Use DISTINCT for distinct elements and then length to get the size of array −

db.yourCollectionName.distinct('yourFieldName').length;

Let us first create a collection with documents −

> db.countOrSizeDemo.insertOne({"StudentFirstName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd304f5b64f4b851c3a13dc")
}
> db.countOrSizeDemo.insertOne({"StudentFirstName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd304fab64f4b851c3a13dd")
}
> db.countOrSizeDemo.insertOne({"StudentFirstName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd304fcb64f4b851c3a13de")
}
> db.countOrSizeDemo.insertOne({"StudentFirstName":"Carol"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd30500b64f4b851c3a13df")
}
> db.countOrSizeDemo.insertOne({"StudentFirstName":"Sam"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd30505b64f4b851c3a13e0")
}
> db.countOrSizeDemo.insertOne({"StudentFirstName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd3050ab64f4b851c3a13e1")
}

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

> db.countOrSizeDemo.find();

This will produce the following output −

{ "_id" : ObjectId("5cd304f5b64f4b851c3a13dc"), "StudentFirstName" : "John" }
{ "_id" : ObjectId("5cd304fab64f4b851c3a13dd"), "StudentFirstName" : "David" }
{ "_id" : ObjectId("5cd304fcb64f4b851c3a13de"), "StudentFirstName" : "David" }
{ "_id" : ObjectId("5cd30500b64f4b851c3a13df"), "StudentFirstName" : "Carol" }
{ "_id" : ObjectId("5cd30505b64f4b851c3a13e0"), "StudentFirstName" : "Sam" }
{ "_id" : ObjectId("5cd3050ab64f4b851c3a13e1"), "StudentFirstName" : "John" }

Following is the query to get the size of a query array −

> db.countOrSizeDemo.distinct('StudentFirstName').length;

This will produce the following output −

4
raja
Published on 22-May-2019 11:42:00
Advertisements