다음은 커서를 사용하여 컬렉션을 반복하는 구문입니다.
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() 메서드를 사용하여 컬렉션의 모든 문서를 표시하는 쿼리입니다.
> 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
}