Mongo $exists query does not return correct documents

后端 未结 1 1307
无人共我
无人共我 2021-01-15 04:14

Honestly, I don\'t understand how this is even possible:

> db.ts.find({\"bcoded_metadata\" : { \"$exists\" : true} } ).count()
199049
> db.ts.find({\"b         


        
相关标签:
1条回答
  • 2021-01-15 04:39

    This is because you use a sparse index for bcoded_metadata. If you have a sparse index on bcoded_metadata, then the index will not contain the documents that don't have the field bcoded_metadata. The documents without the bcoded_metadata field are not part of your original query, and hence "count" will return 0.

    If you run just the find: db.ts.find({"bcoded_metadata" : { "$exists" : false } }) then you won't get any results either. You can either use a non-sparse index, or do a full count with db.ts.count(); and subtract the result of db.ts.find({"bcoded_metadata" : { "$exists" : true } }) result.

    There is a JIRA ticket that explains it a bit more, and can be tracked in case MongoDB acquires an error/warning message for this: https://jira.mongodb.org/browse/SERVER-3918

    0 讨论(0)
提交回复
热议问题