简体   繁体   中英

MongoDB Motor - Cannot $push into nested array using variables

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.

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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