0

I am using mongoDB version 3.6.3 on a ubuntu operating system. I have created a collection with 100 records

To manipulate the data on the mongo shell I assign cursor like below

cur = db.dummyData.find({}, {_id: 0})

now the cur.count() is 100 but cur.toArray().length is 80.

I not sure why this is happening. I have tried with bunch of different collections toArray() length is always 20 less than the actual count.

Would appreciate any help to understand this behavior.

at07
  • 56
  • 5
  • And what happen if you go through that cursor with .foreach() and count rounds? I guess you will get that 100. – JJussi Apr 26 '20 at 10:28
  • Tried that as well, foreach is also going to 80. – at07 Apr 26 '20 at 15:07
  • The current 3.6 version is 3.6.17, you should upgrade to that version first . – D. SM Apr 26 '20 at 15:26
  • Docs: `.count does not perform the query but instead counts the results that would be returned by the query.` Use `.itcount()` – Valijon Apr 26 '20 at 20:15
  • count() is giving me the output i expect. My problem is while iterating over the documents I am able to iterate over only 80 documents not 100 – at07 Apr 27 '20 at 11:08

1 Answers1

1

MongoDB keeps a running count of documents for each collection which is updated for each insert/delete operation. Some occurrences such a hard shutdown can result in this number in the metadata differing from the actual collection.

The cursor.count() function queries the MongoDB asking for this number from the metadata without fetching any documents, so it is very fast. The cursor.itcount() function will actually fetch the documents, so it will run slower, but will always return an accurate count.

To correct the count in the collections metadata, run db.collectionName.validate(true) on the collection in question from the mongo shell.

Joe
  • 25,000
  • 3
  • 22
  • 44
  • count() function is giving me accurate result but when I assign the cursor to a variable and iterate over it, I can see only 80 documents not 100. – at07 Apr 27 '20 at 16:23
  • What makes you think there are 100 documents if the cursor only returns 80? – Joe Apr 27 '20 at 16:40
  • ```.count()``` is returning 100. but when I iterate over the cursor I get only 80 documents – at07 Apr 28 '20 at 13:02
  • And since `count()` is known to be inaccurate at times, what makes you think it is correct this time? Try using `itcount()` which actually counts the documents instead of returning the metadata, and if they don't agree, run `validate` on the collection – Joe Apr 28 '20 at 17:30