sid297
sid297

Reputation: 65

MongoDB Query Failing

I have saved the below query as med.js

var cust = db.Collection.find({"email":null});
var count = 0;
print("total entries: ",cust.length(),"  ",cust.hasNext());
while(cust.hasNext()){
nextCust = cust.next();
db.Collection.update({_id:nextCust._id},{$set : {"email":""}});
count++;
}
print("total updated: ",count);

When I am executing this Query as
mongo dbName --port 13017 ~/Documents/med.js

output is total entries: 491502 false
total updated: 0

How come total entries are showing as 491502 but hasNext() is false. its not going in the while loop

Upvotes: 1

Views: 465

Answers (2)

satish chennupati
satish chennupati

Reputation: 2650

There are three different methods you can use in this context.

  • cursor.count() Modifies the cursor to return the number of documents in the result set rather than the documents themselves.

  • cursor.itcount() Computes the total number of documents in the cursor client-side by fetching and iterating the result set.

  • cursor.size() Returns a count of the documents in the cursor after applying skip() and limit() methods.

cursor.length is not a recommended approach.

Upvotes: 3

ares
ares

Reputation: 4413

The cursor.length() function exhausts the cursor by converting it into an array. Check the function code.

>cur.length
function (){
    return this.toArray().length;
}

Hence you're getting false.

To get the count without exhausting the cursor, use cursor.count()

Upvotes: 4

Related Questions