Count unique items in array-based fields across all MongoDB documents?

MongoDBDatabaseBig Data Analytics

To count unique items in array-based fields, use $group along with aggregate(). Let us create a collection with documents −

> db.demo493.insertOne({"SubjectName":["MySQL","MongoDB","Java"]});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e849f97b0f3fa88e22790c4")
}
> db.demo493.insertOne({"SubjectName":["C++","MongoDB","C"]});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e849fa4b0f3fa88e22790c5")
}
> db.demo493.insertOne({"SubjectName":["MySQL","MongoDB","C"]});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e849fb2b0f3fa88e22790c6")
}

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

> db.demo493.find();

This will produce the following output −

{ "_id" : ObjectId("5e849f97b0f3fa88e22790c4"), "SubjectName" : [ "MySQL", "MongoDB",
"Java" ] }
{ "_id" : ObjectId("5e849fa4b0f3fa88e22790c5"), "SubjectName" : [ "C++", "MongoDB", "C" ] }
{ "_id" : ObjectId("5e849fb2b0f3fa88e22790c6"), "SubjectName" : [ "MySQL", "MongoDB", "C"
] }

Following is the query to count unique items in array-based fields across all documents −

> db.demo493.aggregate([
...    { $unwind: "$SubjectName" },
...    { $group: { _id: "$SubjectName", Frequency: { $sum : 1 } } }
... ]
... );

This will produce the following output −

{ "_id" : "C++", "Frequency" : 1 }
{ "_id" : "C", "Frequency" : 2 }
{ "_id" : "Java", "Frequency" : 1 }
{ "_id" : "MySQL", "Frequency" : 2 }
{ "_id" : "MongoDB", "Frequency" : 3 }
raja
Published on 13-May-2020 05:29:13
Advertisements