您需要在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