Mongo $存在查询未返回正确的文档 [英] Mongo $exists query does not return correct documents
问题描述
老实说,我什至不知道这怎么可能:
Honestly, I don't understand how this is even possible:
> db.ts.find({"bcoded_metadata" : { "$exists" : true} } ).count()
199049
> db.ts.find({"bcoded_metadata" : { "$exists" : false} } ).count()
0
> db.ts.count()
2507873
我认为第一和第二个查询的总和必须等于第三个.
I think sum of the first and second queries must be equal to the third.
我需要从集合中选择所有不存在"bcoded_metadata"但查询不返回任何内容的元素. 当我在简单的python脚本中迭代此集合并手动检查是否存在"bcoded_metadata"时,一切正常.
I need to select from the collection all elements for which "bcoded_metadata" does not exist but the query returns nothing. When I iterate this collection in the simple python script and manually check whether "bcoded_metadata" exists everything works as expected.
from pymongo import Connection
connection = Connection('127.0.0.1', 27017)
db = connection.data
c = 0
for item in db.ts.find():
if not "bcoded_metadata" in item.keys():
c+= 1
print c
python test.py
2308824
这是正确的答案.
问题根源在哪里?
索引:
> db.ts.getIndexes();
[
{
"name" : "_id_",
"ns" : "data.ts",
"key" : {
"_id" : 1
},
"v" : 0
},
{
"_id" : ObjectId("4f3c299b4c4a5ccfddbe4069"),
"ns" : "data.ts",
"key" : {
"last_seen" : 1
},
"name" : "last_seen_1",
"v" : 0
},
{
"_id" : ObjectId("4f3c2cef4c4a5ccfddbe406a"),
"ns" : "data.ts",
"key" : {
"attempts" : -1
},
"name" : "attempts_-1",
"v" : 0
},
{
"_id" : ObjectId("4f4279ed6aca13be31acbe6d"),
"ns" : "data.ts",
"key" : {
"bcoded_metadata" : 1
},
"name" : "bcoded_metadata_1",
"sparse" : true,
"v" : 0
}
]
推荐答案
这是因为您对bcoded_metadata
使用了稀疏索引.如果bcoded_metadata上的索引稀疏,则该索引将不包含没有字段bcoded_metadata
的文档.没有bcoded_metadata
字段的文档不是原始查询的一部分,因此"count"将返回0.
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.
如果仅运行查找:db.ts.find({"bcoded_metadata" : { "$exists" : false } })
,则也不会得到任何结果.您可以使用非稀疏索引,也可以使用db.ts.count();
进行全计数并减去db.ts.find({"bcoded_metadata" : { "$exists" : true } })
结果的结果.
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.
有一个JIRA票证可以解释得更多,如果MongoDB为此获取错误/警告消息,可以进行跟踪:
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
这篇关于Mongo $存在查询未返回正确的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!