简体   繁体   English

如何使用 MongoDB/pyMongo 使字段路径在同一文档中包含一个值?

[英]How do I make a field path include a value in same document using MongoDB/pyMongo?

The documents in the MongoDB I am querying can be stripped down to this as an example:我查询的 MongoDB 中的文档可以简化为以下示例:

{
    "date":"2019-08-15",
    "status":"5345",
    "foo":
    {
        "bar":
        {
            "years":
            {
                "2018":
                {
                    "const":1234
                },
                "2019":
                {
                    "const":4321
                }
            }
        }
    }
}

I am trying to get the "const" values from this document using pyMongo.我正在尝试使用 pyMongo 从本文档中获取“const”值。

The keys in "years" is varying with the "date" of the document. “年”中的键随文档的“日期”而变化。

I have attempted to use this pipeline where I try to use the year of "date" to get the "const" from this year:我试图使用这个管道,我尝试使用“日期”的年份来获取今年的“常量”:

pipeline=[
    {'$match':{'status':{'$exists': True}}},
    {'$project':
        'const_thisYear':{
            '$let':{
                'vars':{
                    'yr':{ '$year': {'$convert':{'input': '$date','to': 'date'}}},
                    'res': '$foo.bar.years'
                },
                'in': '$$res.$$yr.const'
            }
        }
    }
]

When aggregating I get the following python exception:聚合时,我得到以下 python 异常:

OperationFailure: FieldPath field names may not start with '$'.

How do I do this correctly?我该如何正确地做到这一点?

Python 3.7.7 Python 3.7.7

You should revise your collection structure to not store data as keys;您应该修改您的集合结构以不将数据存储为键; but irrespective, just using regular python dict manipulation can get you out of the hole:但无论如何,只需使用常规的 python dict 操作就可以让你摆脱困境:

for doc in db.mycollection.find({'status': {'$exists': True}}, {'foo.bar.years': 1}):
    for year, year_value in doc['foo']['bar']['years'].items():
        print(year, year_value.get('const'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM