आप MongoDB में count() मेथड के प्रदर्शन को बढ़ाने के लिए ensureIndex() का उपयोग कर सकते हैं। कॉन्सेप्ट समझने के लिए, एक दस्तावेज़ के साथ एक संग्रह बनाते हैं। दस्तावेज़ के साथ संग्रह बनाने की क्वेरी इस प्रकार है:
> db.countPerformanceDemo.insertOne({"StudentName":"John","StudentCountryName":"US"}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ebcf82f684a30fbdfd55f") } > db.countPerformanceDemo.insertOne({"StudentName":"Mike","StudentCountryName":"UK"}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ebd042f684a30fbdfd560") } > db.countPerformanceDemo.insertOne({"StudentName":"David","StudentCountryName":"AUS"}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ebd112f684a30fbdfd561") } > db.countPerformanceDemo.insertOne({"StudentName":"Carol","StudentCountryName":"US"}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ebd1a2f684a30fbdfd562") } > db.countPerformanceDemo.insertOne({"StudentName":"Bob","StudentCountryName":"UK"}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ebd212f684a30fbdfd563") } > db.countPerformanceDemo.insertOne({"StudentName":"David","StudentCountryName":"UK"}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ebd9a2f684a30fbdfd564") } > db.countPerformanceDemo.insertOne({"StudentName":"David","StudentCountryName":"US"}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ebd9e2f684a30fbdfd565") }
find() विधि की मदद से संग्रह से सभी दस्तावेज़ प्रदर्शित करें। क्वेरी इस प्रकार है:
> db.countPerformanceDemo.find().pretty();
आउटपुट निम्न है:
{ "_id" : ObjectId("5c8ebcf82f684a30fbdfd55f"), "StudentName" : "John", "StudentCountryName" : "US" } { "_id" : ObjectId("5c8ebd042f684a30fbdfd560"), "StudentName" : "Mike", "StudentCountryName" : "UK" } { "_id" : ObjectId("5c8ebd112f684a30fbdfd561"), "StudentName" : "David", "StudentCountryName" : "AUS" } { "_id" : ObjectId("5c8ebd1a2f684a30fbdfd562"), "StudentName" : "Carol", "StudentCountryName" : "US" } { "_id" : ObjectId("5c8ebd212f684a30fbdfd563"), "StudentName" : "Bob", "StudentCountryName" : "UK" } { "_id" : ObjectId("5c8ebd9a2f684a30fbdfd564"), "StudentName" : "David", "StudentCountryName" : "UK" } { "_id" : ObjectId("5c8ebd9e2f684a30fbdfd565"), "StudentName" : "David", "StudentCountryName" : "US" }
count() के उच्च-प्रदर्शन रूप को प्राप्त करने की क्वेरी यहाँ है:
> db.countPerformanceDemo.ensureIndex({"StudentName":1}); { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
अब, count() मेथड लागू करें। यह "David" StudentName वाले रिकॉर्ड गिनता है:
> db.countPerformanceDemo.find({"StudentName":"David"}).count();
आउटपुट निम्न है:
3