find() 커서와 함께 while 루프의 도움으로 사용자 정의 논리를 사용해야 합니다. 문서로 컬렉션을 만들자 −
> 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