distinct() और length का उपयोग
किसी फील्ड के **अद्वितीय (distinct) मानों की संख्या** गिनने के लिए, distinct() मेथड (जो अद्वितीय मानों की सरणी लौटाता है) पर length प्रॉपर्टी एक्सेस करें।
सिंटैक्स
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();
आउटपुट (6 दस्तावेज़, 4 अद्वितीय नाम):
अद्वितीय मान गिनना
> db.countDistinctDemo.distinct("StudentName").length; 4व्याख्या:
distinct("StudentName")सरणी["John", "Chris", "Carol", "David"]लौटाता है (क्रम भिन्न हो सकता है)। इसकी.length4 है।बड़े संग्रह के लिए: एग्रीगेशन पाइपलाइन
{$group: {_id: "$StudentName"}}, {$count: "total"}अधिक स्केलेबल है क्योंकिdistinctके पास परिणाम आकार सीमा (16MB) होती है।