$ push объект во вложенный массив - PullRequest
0 голосов
/ 26 мая 2019

Я ищу способ $ push-объекта во вложенный массив, ключи маршрута которого поступают из переменных.

{
    "_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']}
        }
    })

Таким образом, маршрут в объекте "history" исходит изтело:

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

, и я хочу добавить в массив объект с:

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

1 Ответ

1 голос
/ 27 мая 2019

получил, для кого-то еще, кто мог бы искать ответ;

Хитрость заключается в том, чтобы установить переменную с требуемым путем, используя переменные и требуемое значение, а затем нажать только эту конечную переменную.

    # 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
    })

...