1

I am trying to update a nested array in my mongodb document, and I cant figure out how to $push using variables in such a nested array. The docs say to use the dot notation but I cant use that since I have different key and node_id against which I need to $push

for key, value in docs.items():
    print(f'Key: {key} Value: {value}')
    for node_id, timestamp in value.items():
    result = await db[collection].update_one({'user_id': user_id, 'date': date}, {'$push':{"key.node_id": timestamp}}, upsert=True)
return result.modified_count

value is a nested dictionary inside docs. Using the above code just updates the document with str 'key' and 'node_id'. How do I access variables using dot notation in this case?

UPDATE:

This is a sample document that I am trying to build

{
  "date": "18/04/2020",
  "user_id": "my_user",
  "standing": [
    { "2": [1582805181, 1582805183] },
    { "3": [1582805181, 1582805183] }
  ],
  "sitting": [
    { "2": [1582805181, 1582805183] },
    { "3": [1582805181, 1582805183] }
  ],
  "walking": [
    { "2": [1582805181, 1582805183] },
    { "3": [1582805181, 1582805183] }
  ]
}

Update 2:

key will be either one of three sitting, standing, walking. value is a nested dictionary in docs whose keys can be 2 or 3 - node_id in this case and timestamp will be a unix timestamp of 10 digits.

4
  • Please include a sample input document in your post. Commented Apr 20, 2020 at 9:48
  • @prasad_ updated with a sample document Commented Apr 20, 2020 at 9:57
  • Also, tell what are the values in "key.node_id" and timestamp. Are you getting any errors when you run the code? Commented Apr 20, 2020 at 10:06
  • @prasad_ details added as requested Commented Apr 20, 2020 at 10:31

1 Answer 1

1

You can use the $push update operator into a nested array using variables. The variable values are constructed from the provided key and the node_id values.

The following two variables: (i) cond_var is used with the update method's query condition, and (ii) the updt_var is used with the update.

cond_var = key + "." + node_id
updt_var = key + "." + "$" + "." + node_id

result = collection.update_one( { 'user_id': user_id, 'date': date, cond_var: { '$exists': True  } },  
                                { '$push': { updt_var : timestamp } },
                                upsert=True )
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.