$将对象推入嵌套数组

时间:2019-05-26 20:09:11

标签: python mongodb mongodb-query pymongo

我正在寻找一种将对象$推送到路由键来自变量的嵌套数组的方法。

{
    "_id": {
        "$oid": "5ce9964cd0e7df57eb0c8a99"
    },
    "history": {
        "2019": {
            "jan": {
                "1": [],
                "2": [],
                "3": []
            },
            "feb": {
                "1": [],
                "2": [],
                "3": []
            }
        }
    }
}
def add_tx():
    body = request.get_json()
    users = mongo.db.date
    users.find_one_and_update({
        "username": session['username']
    }, {
        '$push': {
            'history'[str(body['year'])][months[body['month']]][str(
                body['day'])]: {body['title']: body['value']}
        }
    })

因此“历史”对象中的路线来自正文:

body['year'], body['month'], body['day']

,我想将一个对象附加到:

{body['title']: body['value']}

1 个答案:

答案 0 :(得分:1)

为其他可能正在寻找答案的人明白了

诀窍是使用变量和期望值设置具有所需路径的变量,然后仅推送最终变量。

    # Setting the variable with the complete path in the DB using the variables from the POST BODY
    query = {}
    query['history.' + str(body['year']) + "." + months[body['month']] +
          "." + str(body['day'])] = {body['title']: float(body['value'])}
    # Pushing the created variable to the DB
    users.find_one_and_update({
        "username": session['username']
    }, {
        '$push': query
    })