MongoDB में कर्सर का उपयोग करके कलेक्शन के माध्यम से लूप करना
MongoDB में कर्सर के साथ कलेक्शन के माध्यम से लूप करने का सिंटैक्स निम्नलिखित है:
var anyVariableName1;
var anyVariableName2 = db.yourCollectionName.find();
while(yourVariableName2.hasNext()) {
yourVariableName1 = yourVariableName2.next();
printjson(yourVariableName1);
};
उदाहरण: दस्तावेज़ों के साथ एक कलेक्शन बनाना
आइए दस्तावेज़ों के साथ एक कलेक्शन बनाते हैं। निम्नलिखित क्वेरी है:
> db.loopThroughCollectionDemo.insertOne({"StudentName":"John","StudentAge":23});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ca81f2d6669774125247f") }
> db.loopThroughCollectionDemo.insertOne({"StudentName":"Larry","StudentAge":21});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ca8272d66697741252480") }
> db.loopThroughCollectionDemo.insertOne({"StudentName":"Chris","StudentAge":25});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ca8462d66697741252481") }
>> db.loopThroughCollectionDemo.insertOne({"StudentName":"Robert","StudentAge":24});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ca8632d66697741252482") }
find() मेथड से सभी दस्तावेज़ प्रदर्शित करना
कलेक्शन से सभी दस्तावेज़ प्रदर्शित करने के लिए find() मेथड का उपयोग करने का क्वेरी:
> db.loopThroughCollectionDemo.find().pretty();
यह निम्नलिखित आउटपुट देगा:
{ "_id" : ObjectId("5c9ca81f2d6669774125247f"), "StudentName" : "John", "StudentAge" : 23 }
{ "_id" : ObjectId("5c9ca8272d66697741252480"), "StudentName" : "Larry", "StudentAge" : 21 }
{ "_id" : ObjectId("5c9ca8462d66697741252481"), "StudentName" : "Chris", "StudentAge" : 25 }
{ "_id" : ObjectId("5c9ca8632d66697741252482"), "StudentName" : "Robert", "StudentAge" : 24 }
कर्सर के साथ कलेक्शन के माध्यम से लूप करने का क्वेरी
> var allDocumentValue;
> var collectionName = db.loopThroughCollectionDemo.find();
> while(collectionName.hasNext()){
allDocumentValue = collectionName.next();
printjson(allDocumentValue);
}
यह निम्नलिखित आउटपुट देगा:
{ "_id" : ObjectId("5c9ca81f2d6669774125247f"), "StudentName" : "John", "StudentAge" : 23 }
{ "_id" : ObjectId("5c9ca8272d66697741252480"), "StudentName" : "Larry", "StudentAge" : 21 }
{ "_id" : ObjectId("5c9ca8462d66697741252481"), "StudentName" : "Chris", "StudentAge" : 25 }
{ "_id" : ObjectId("5c9ca8632d66697741252482"), "StudentName" : "Robert", "StudentAge" : 24 }