如何统计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