如何在使用遊標的情況下迴圈遍歷 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() 方法從集合中顯示所有文件的查詢

> 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
}

更新於: 2019 年 7 月 30 日

1K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告