0

I am looking for a way to $push an object to a nested array which the route keys come from variables.

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

So the route in the "history" object comes from the body:

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

and I want to append to the array an object with:

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

1 Answer 1

1

got it, for someone else that could be looking for the answer;

the trick is to set a variable with the wanted path using the variables and the wanted value then push only that final variable.

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.