【问题标题】:How would I find documents based on whether a field exists AND another that doesn't, in MongoDB?在 MongoDB 中,如何根据一个字段是否存在和另一个字段不存在来查找文档?
【发布时间】:2018-12-28 00:46:08
【问题描述】:

我有一堆由“数据”和“文本”字段组成的文档。有些文档有任何一个,而有些则没有。我将如何通过 pyMongo 查询以获取具有“数据”字段但没有“文本”字段的文档?

我尝试了以下查询,但 mongo 没有返回任何文件。

方法一:

files = collection.find({"Data": {"$exists": "true"}, {"Text": {"$exists": "false"}})

for file in files:
    print(file)

方法 2:

files = collection.find({"$and": [{"Data": {"$exists": "true"}}, {"Text": {"$exists": "false"}}]})

for file in files:
    print(file)

注意:我目前正在尝试在没有集合具有“文本”字段(尚未)的数据库上进行查询,但查询仍应按逻辑工作。它是:

返回带有“数据”但没有“文本”的文档

【问题讨论】:

  • 试试"$exists": true而不是"$exists": "true"
  • 嘿,我正在使用 pyMongo,它是 MongoDB 的原生 python 驱动程序,它只接受字符串中的命令。命令 files = collection.find({"Data": {"$exists": "true"}) 运行良好。

标签: python mongodb pymongo


【解决方案1】:

你可以参考这个链接:https://docs.mongodb.com/manual/tutorial/query-for-null-fields/

试试这个

  collection.find({"Data": {"$exists": "true"}, {"Text": null })

查询匹配包含值为 null 的 Text 字段或 不包含文本字段。

如果您无法解决此问题,请将您的数据存储发布到集合中 参考和您的架构结构。如果您有问题,这将帮助我们。

【讨论】:

    【解决方案2】:

    正如 Anushka 指出的那样,我尝试使用 None 而不是 False,它确实有效。

    files = coll.find({"Data": {"$exists": "true"}, "Text": None})
    

    如果有人知道为什么我如下所述的最初尝试没有奏效,请对此答案发表评论。谢谢。

    files = collection.find({"Data": {"$exists": "true"}, {"Text": {"$exists": "false"}})
    

    【讨论】:

    • 啊,刚刚注意到,您将 Text 部分包装到它自己的哈希/对象中(并且您在某处缺少一个右花括号)跨度>
    • 你是对的!我没有注意到那里。但是我在正确版本的代码中用“false”替换了 None/Null(请参阅接受的答案),但仍然不起作用。奇怪。
    【解决方案3】:

    在使用 $exists:true 时,任何类型的索引使用都超出了等式。您可以将查询修改为 files = collection.find({"Data":{$ne:null}, Text:null})

    【讨论】:

    • $ne: null 似乎并不比$exists: true/false 更容易被索引支持。 (事实上​​,直到几个版本之前它才使用索引)。你有支持这种说法的来源吗?
    • 我没有任何来源,但一般来说,当我在 prod 中运行查询时,$exists 的运行速度比 e:{$nin:[null,""]} 当 e 被索引时运行得慢。其次,空值没有被索引,因此索引中存在的所有值都会被删除。
    • “第二个空值不被索引” - 它们是,even in a sparse index
    • 在我的机器上测试过,确实,$exists 查询使用了相应的索引。
    • 请检查:stackoverflow.com/questions/8176310,请您确认您的索赔
    猜你喜欢
    • 2018-12-14
    • 2023-03-07
    • 1970-01-01
    • 2021-11-09
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多