MongoDB में कर्सर इटरेट करके डॉक्यूमेंट्स प्रिंट करना
MongoDB में find() से लौटे कर्सर को इटरेट करके प्रत्येक डॉक्यूमेंट प्रिंट करने के लिए forEach() के साथ printjson का उपयोग करें।
उदाहरण: कलेक्शन और डॉक्यूमेंट्स बनाना
> db.cursorDemo.insertOne({"StudentFullName":"John Smith","StudentAge":23});
{ "acknowledged" : true, "insertedId" : ObjectId("5cc7f0d08f9e6ff3eb0ce442") }
> db.cursorDemo.insertOne({"StudentFullName":"John Doe","StudentAge":21});
{ "acknowledged" : true, "insertedId" : ObjectId("5cc7f0df8f9e6ff3eb0ce443") }
> db.cursorDemo.insertOne({"StudentFullName":"Carol Taylor","StudentAge":20});
{ "acknowledged" : true, "insertedId" : ObjectId("5cc7f0eb8f9e6ff3eb0ce444") }
> db.cursorDemo.insertOne({"StudentFullName":"Chris Brown","StudentAge":24});
{ "acknowledged" : true, "insertedId" : ObjectId("5cc7f0f88f9e6ff3eb0ce445") }
सभी डॉक्यूमेंट्स देखना
> db.cursorDemo.find().pretty();
आउटपुट:
{ "_id" : ObjectId("5cc7f0d08f9e6ff3eb0ce442"), "StudentFullName" : "John Smith", "StudentAge" : 23 }
{ "_id" : ObjectId("5cc7f0df8f9e6ff3eb0ce443"), "StudentFullName" : "John Doe", "StudentAge" : 21 }
{ "_id" : ObjectId("5cc7f0eb8f9e6ff3eb0ce444"), "StudentFullName" : "Carol Taylor", "StudentAge" : 20 }
{ "_id" : ObjectId("5cc7f0f88f9e6ff3eb0ce445"), "StudentFullName" : "Chris Brown", "StudentAge" : 24 }
कर्सर इटरेट करके सभी डॉक्यूमेंट्स प्रिंट करना
> db.cursorDemo.find().forEach(printjson);
आउटपुट:
{ "_id" : ObjectId("5cc7f0d08f9e6ff3eb0ce442"), "StudentFullName" : "John Smith", "StudentAge" : 23 }
{ "_id" : ObjectId("5cc7f0df8f9e6ff3eb0ce443"), "StudentFullName" : "John Doe", "StudentAge" : 21 }
{ "_id" : ObjectId("5cc7f0eb8f9e6ff3eb0ce444"), "StudentFullName" : "Carol Taylor", "StudentAge" : 20 }
{ "_id" : ObjectId("5cc7f0f88f9e6ff3eb0ce445"), "StudentFullName" : "Chris Brown", "StudentAge" : 24 }
केवल विशिष्ट फील्ड्स प्रिंट करना
> db.cursorDemo.find({}, { "StudentFullName": 1, "StudentAge": 1, "_id": 0 }).forEach(printjson)
आउटपुट:
{ "StudentFullName" : "John Smith", "StudentAge" : 23 }
{ "StudentFullName" : "John Doe", "StudentAge" : 21 }
{ "StudentFullName" : "Carol Taylor", "StudentAge" : 20 }
{ "StudentFullName" : "Chris Brown", "StudentAge" : 24 }
अन्य उपयोगी मेथड्स:
print()- कॉम्पैक्ट फॉर्मेट में प्रिंटprintjsononeline()- सिंगल लाइन JSON- कस्टम फंक्शन:
.forEach(function(doc) { print(doc.StudentFullName); }) toArray()- सभी डॉक्यूमेंट्स को ऐरे में कन्वर्ट:db.cursorDemo.find().toArray()