Home > Net >  MongoDB returns different values from count() and find() for same filters
MongoDB returns different values from count() and find() for same filters

Time:11-27

I am running a MongoDB 6.0.3 replica set. I have a collection of products and I want to get the count of products matching my filters. However, when I run find(), I get about 23 results returned, but when I run count(), I get a count of 706 matching documents. What could be the issue here?

replicaset-01 [primary] mydb> db.products.find({company_name:"Acme", image:''}).count()
706
replicaset-01 [primary] mydb> db.products.find({company_name:"Acme", image:''}, {_id:1})
[
  { _id: ObjectId("636bd5459a8d7621aa490a03") },
  { _id: ObjectId("636bd5459a8d7621aa490b46") },
  { _id: ObjectId("636bd5459a8d7621aa490b0e") },
  { _id: ObjectId("636bd5459a8d7621aa490b4d") },
  { _id: ObjectId("636bd5459a8d7621aa4909a2") },
  { _id: ObjectId("636bd5459a8d7621aa490b06") },
  { _id: ObjectId("636bd5459a8d7621aa4909a3") },
  { _id: ObjectId("636bd5469a8d7621aa490c52") },
  { _id: ObjectId("636bd5469a8d7621aa490d12") },
  { _id: ObjectId("636bd5469a8d7621aa490c98") },
  { _id: ObjectId("636bd5459a8d7621aa490949") },
  { _id: ObjectId("636bd5459a8d7621aa4909e3") },
  { _id: ObjectId("636bd5459a8d7621aa490a80") },
  { _id: ObjectId("636bd5459a8d7621aa490b6d") },
  { _id: ObjectId("636bd5459a8d7621aa4909eb") },
  { _id: ObjectId("636bd5459a8d7621aa490b50") },
  { _id: ObjectId("636bd5469a8d7621aa490b93") },
  { _id: ObjectId("636bd5459a8d7621aa490940") },
  { _id: ObjectId("636bd5479a8d7621aa4911a1") },
  { _id: ObjectId("636bd5479a8d7621aa491070") }
]

CodePudding user response:

Both of your mongosh commands are executing as designed.

  • db.collection.find(...).count() will provide the total document count of find.
  • db.collection.find(...) will print the first 20 documents.

The perhaps surprising, and important point here (from the docs):

"Executing db.collection.find() in mongosh automatically iterates the cursor to display up to the first 20 documents. Type it to continue iteration."

  • Related