如何統計MongoDB 中游標的迭代次數?
您需要使用 while 迴圈以及 find() 遊標的幫助來使用自定義邏輯。讓我們建立一個帶有文件的集合 -
> db.demo724.insertOne(
... {
... details:
... {
... id:101,
... otherDetails:[
... {Name:"Chris"}
... ]
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5eab0cce43417811278f5890")
}
>
>
> db.demo724.insertOne(
... {
...
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5eab0cce43417811278f5891")
}
> db.demo724.insertOne(
... {
... details:
... {
... id:1001
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5eab0cce43417811278f5892")
}利用 find() 方法從集合中顯示所有文件 -
> db.demo724.find();
這將生成以下輸出 &miinus;
{ "_id" : ObjectId("5eab0cce43417811278f5890"), "details" : { "id" : 101, "otherDetails" : [ { "Name" : "Chris" } ] } }
{ "_id" : ObjectId("5eab0cce43417811278f5891") }
{ "_id" : ObjectId("5eab0cce43417811278f5892"), "details" : { "id" : 1001 } }這是在 MongoDB 中統計遊標迭代的查詢 -
> var c=db.demo724.find();
> var detailsCount=0;
> while (c.hasNext()) {
... var current = c.next();
... if (typeof current["details"] != "undefined") {
... detailsCount++;
... }
... }
1
> print("number of details: " + detailsCount);這會產生以下輸出 -
number of details: 2
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP