【问题标题】:Why doesn't this pymongo subdocument find work?为什么这个 pymongo 子文档找不到工作?
【发布时间】:2021-06-02 04:30:10
【问题描述】:

我正在考虑使用 mongodb,到目前为止,我尝试过的大多数事情都有效。但我不知道为什么这个发现不起作用。

col = db.create_collection("test")
x = col.insert_many([
    {"item": "journal", "qty": 25, "size": {"h": 14, "w": 21, "uom": "cm"}, "status": "A"},
    {"item": "notebook", "qty": 50, "size": {"h": 8.5, "w": 11, "uom": "in"}, "status": "A"},
    {"item": "paper", "qty": 100, "size": {"h": 8.5, "w": 11, "uom": "in"}, "status": "D"},
    {"item": "planner", "qty": 75, "size": {"h": 22.85, "w": 30, "uom": "cm"}, "status": "D"},
    {"item": "postcard", "qty": 45, "size": {"h": 10, "w": 15.25, "uom": "cm"}, "status": "A"}
])

cursor = col.find({"size": {"h": 14, "w": 21, "uom": "cm"}})
if cursor.retrieved == 0:
    print("found nothing")          # <<<<<<<<< prints this

【问题讨论】:

    标签: mongodb find pymongo subdocument


    【解决方案1】:

    我在想如果 cursor.retrived 找到了一些东西,它就不是零。我猜不会。我发现这行得通:

    lst = list(cursor)
    print(lst)
    
    cursor.rewind()
    print(list(cursor))
    
    if len(lst) != 0:
        for d in lst:
            print(d)
    

    【讨论】:

      【解决方案2】:

      正如docs 中在匹配嵌入式/嵌套文档部分中解释的那样:

      整个嵌入文档的相等匹配需要指定文档的完全匹配,包括字段顺序。

      因此,您必须按照 DB 中存在的相同顺序将对象设置到 find 阶段。

      我真的不知道对象的键是否遵循严格的顺序(按字母顺序或其他顺序),但使用 this 查询几乎所有内容都会输出结果。并非总是如此,我认为有一个“随机”(或无法处理)的概念来存储数据 - 至少到 mongo 游乐场 - 。

      顺便说一句,确保结果的正确方法是使用dot notation,因此this 查询将始终正常工作。

      coll.find({
        "size.h": 14,
        "size.w": 21,
        "size.uom": "cm"
      })
      

      【讨论】:

      • 我查看了这些链接并尝试了变体,但仍然没有得到任何结果。我想我应该说我正在使用 pymongo (python)。也许这会造成差异?
      • PyMongo 在钩子下使用 Mongo 工作。 python 代码没有魔法,所以 Mongo 文档对 pymongo 有效。
      • cursor = col.find({"size.h": 14, "size.w": 21, "size.uom": "cm"}) 我试过了,cursor.retrived 仍然为零。如果我打印整个集合,它就在那里。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 2018-03-13
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多