【问题标题】:MongoDB query doesn't behave as expected with nested elementsMongoDB 查询与嵌套元素的行为不符
【发布时间】:2016-04-10 14:05:40
【问题描述】:

我正在尝试返回与值匹配且与子属性匹配的结果。所以我想返回匹配月份的结果,然后匹配一系列值。然而,我发现即使是简单的搜索,似乎也没有返回任何我期望的结果。

使用 pymongo 我的查询是:

month = 2
results = db.master.find({"months": str(month)})

这肯定会返回正确月份的所有匹配文档。但是我没有得到月份 = 2 的记录返回

我的数据在 MDB 中存储为:

{
    "_id": {
        "$oid": "568d0bebc1bed847da7a2e6f"
    },
    "months": {
        "2": {
            "std_rank": 0.11338862902393358,
            "rank_gain": 0.6183933826187626,
            "gain": 0.9618213660245183,
            "std": 0.021891473641317716
        },
    "months": {
        "3": {
            "std_rank": 0.11338862902393358,
            "rank_gain": 0.6183933826187626,
            "gain": 0.9618213660245183,
            "std": 0.021891473641317716
        },   
    },
    "code": "VU"
}

一个建议的答案适用于过滤正确的月份,现在的问题是如何将过滤器应用于其子元素。例如:

results = db.master.find({}, {"_id": 0, "months." + str(month): 1, "months.std_rank": {"$lte": max_std_rank, "$gte": min_std_rank} } )

我收到以下错误:

pymongo.errors.OperationFailure: database error: Can't canonicalize query: BadValue >1 field in obj: { $gte: 0.0, $lte: 1.0 }

【问题讨论】:

  • 也许您正在寻找投影为db.master.find({}, { "_id": 0, "months.2": 1 })
  • 我不在 python 中工作,但你需要将几个月与 2 连接起来可能类似于month = 2; db.master.find({"months"+str(month): {$exists: true}})
  • @chridam 这有助于将字段范围缩小到月份 = 2,例如,接下来如何过滤子值。
  • 试试results = db.master.find({ "months." + str(month) + ".std_rank": {"$lte": max_std_rank, "$gte": min_std_rank } }, { "_id": 0, "months." + str(month): 1 } )
  • @chridam 谢谢 - 非常有用,MDB 有时感觉很 hacky。为每个人创建一个答案怎么样。

标签: python regex mongodb pymongo


【解决方案1】:

试试下面的查询

results = db.master.find({ "months." + str(month) + ".std_rank": {"$lte": max_std_rank, "$gte": min_std_rank } }, { "_id": 0, "months." + str(month): 1 } )

它使用投影仅返回与给定月份键匹配的文档。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-20
    • 1970-01-01
    • 2021-03-24
    • 2018-02-20
    • 2015-05-20
    • 1970-01-01
    相关资源
    最近更新 更多