भिन्न मान गिनने के लिए लंबाई की अवधारणा का उपयोग करें। निम्नलिखित वाक्य रचना है -
db.yourCollectionName.distinct("yourFieldName").length; आइए दस्तावेजों के साथ एक संग्रह बनाएं -
> db.countDistinctDemo.insertOne({"StudentName":"John"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cbd6166de8cc557214c0dfa")
}
> db.countDistinctDemo.insertOne({"StudentName":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cbd616ade8cc557214c0dfb")
}
> db.countDistinctDemo.insertOne({"StudentName":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cbd616cde8cc557214c0dfc")
}
> db.countDistinctDemo.insertOne({"StudentName":"Carol"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cbd6170de8cc557214c0dfd")
}
> db.countDistinctDemo.insertOne({"StudentName":"David"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cbd6175de8cc557214c0dfe")
}
> db.countDistinctDemo.insertOne({"StudentName":"Carol"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cbd6181de8cc557214c0dff")
} संग्रह से सभी दस्तावेज़ों को खोजने () विधि की सहायता से प्रदर्शित करें -
> db.countDistinctDemo.find().pretty();
यह निम्नलिखित आउटपुट देगा -
{ "_id" : ObjectId("5cbd6166de8cc557214c0dfa"), "StudentName" : "John" }
{ "_id" : ObjectId("5cbd616ade8cc557214c0dfb"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5cbd616cde8cc557214c0dfc"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5cbd6170de8cc557214c0dfd"), "StudentName" : "Carol" }
{ "_id" : ObjectId("5cbd6175de8cc557214c0dfe"), "StudentName" : "David" }
{ "_id" : ObjectId("5cbd6181de8cc557214c0dff"), "StudentName" : "Carol" } अलग-अलग मान गिनने के लिए क्वेरी निम्नलिखित है -
> db.countDistinctDemo.distinct("StudentName").length; यह निम्नलिखित आउटपुट देगा -
4