MongoDB query for counting number of unique fields grouped by another field?



For this, use aggregate() and group with $group. Let us create a collection with documents −

> db.demo354.insertOne({"Name1":"Chris","Name2":"David"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e5685a6f8647eb59e5620c0") } > db.demo354.insertOne({"Name1":"Chris","Name2":"David"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e5685a9f8647eb59e5620c1") } > db.demo354.insertOne({"Name1":"Chris","Name2":"Bob"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e5685aff8647eb59e5620c2") } > db.demo354.insertOne({"Name1":"Carol","Name2":"John"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e5685c4f8647eb59e5620c3") } > db.demo354.insertOne({"Name1":"Carol","Name2":"John"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e5685c5f8647eb59e5620c4") }

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

> db.demo354.find();

This will produce the following output −

{ "_id" : ObjectId("5e5685a6f8647eb59e5620c0"), "Name1" : "Chris", "Name2" : "David" } { "_id" : ObjectId("5e5685a9f8647eb59e5620c1"), "Name1" : "Chris", "Name2" : "David" } { "_id" : ObjectId("5e5685aff8647eb59e5620c2"), "Name1" : "Chris", "Name2" : "Bob" } { "_id" : ObjectId("5e5685c4f8647eb59e5620c3"), "Name1" : "Carol", "Name2" : "John" } { "_id" : ObjectId("5e5685c5f8647eb59e5620c4"), "Name1" : "Carol", "Name2" : "John" }

Following is the query for counting number of unique fields grouped by another field −

> db.demo354.aggregate([ ... { ...    $group: { ...       _id: { ...          "Name1": "$Name1", ...          "Name2": "$Name2" ...       }, ...    } ... }, ... { ...    $group: { ...       _id: "$_id.Name1", ...       "Name2": { $sum: 1 } ...    } ... }, ... { ...    $project: { ...       _id: 0, ...       Name1: "$_id", ...       Name2: 1 ...    } ... } ... ])

This will produce the following output −

{ "Name2" : 2, "Name1" : "Chris" } { "Name2" : 1, "Name1" : "Carol" }
Updated on: 2020-04-02T08:07:37+05:30

320 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements