MongoDB Motor-无法使用变量将$$推入嵌套数组中

问题描述 投票:0回答:1

我正在尝试更新mongodb文档中的嵌套数组,但无法弄清楚如何在此类嵌套数组中使用变量$pushdocs说要使用点符号,但是我不能使用它,因为我需要针对keynode_id使用不同的$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

valuedocs内部的嵌套字典。使用上面的代码只需使用str 'key''node_id'更新文档。在这种情况下,如何使用点符号访问变量?

更新:

这是我要构建的样本文档

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

更新2:

key将是坐着,站着,走着的三种之一。 value是文档中的嵌套词典,其键可以是2或3-在这种情况下,node_idtimestamp将是10位数的unix时间戳。

python mongodb pymongo
1个回答
0
投票

您可以将$push更新运算符用于使用变量的嵌套数组中。变量值由提供的keynode_id值构成。

以下两个变量:(i)cond_var与更新方法的查询条件一起使用,并且(ii)updt_var与更新方法一起使用。

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 )
© www.soinside.com 2019 - 2024. All rights reserved.