Sau đây là cú pháp để lặp qua các tập hợp bằng con trỏ
var anyVariableName1;
var anyVariableName2= db.yourCollectionName.find();
while(yourVariableName2.hasNext()) {
yourVariableName1= yourVariableName2.next(); printjson(yourVariableName1);
}; Hãy để chúng tôi tạo một bộ sưu tập với các tài liệu. Sau đây là truy vấn
> 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")
} Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find ()
> db.loopThroughCollectionDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau
{
"_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
} Sau đây là truy vấn lặp qua các bộ sưu tập bằng con trỏ
> var allDocumentValue;
> var collectionName=db.loopThroughCollectionDemo.find();
> while(collectionName.hasNext()){allDocumentValue= collectionName.next();printjson(allDocumentValue);
... } Điều này sẽ tạo ra kết quả sau
{
"_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
}