MongoDB将文档添加到文档列表(如果唯一)

2024-04-19 19:03:53 发布

您现在位置:Python中文网/ 问答频道 /正文

鉴于本文件结构:

{
    "_id": date,
    "list": [
        { hour: "something",
          hour: "something else"
        }
    ]
}
  1. 我如何根据id向上插入新的文档?你知道吗
  2. 如何检查子文档中是否存在密钥并向上插入该密钥?你知道吗

我试过的:

col.update({'_id':my_str}, {'_id':my_str, 'list':{'$addtoset':["14":"yet another thing"]}}, {'$upsert':'true'})

编辑:

更新了我的结构:

{
    _id: date,
    hours: [
                { "0": "something"},
                { "1": "something else"},
                  ...
            ]
}

Tags: 文件文档iddatemy密钥updatecol
1条回答
网友
1楼 · 发布于 2024-04-19 19:03:53

不能用pymongo直接修改内部列表属性,需要拉取整个文档重新发布:

my_doc = col.find_one({'_id': my_str})
if my_doc is not None:
    # Document exist, modify it
    my_doc['hours'].append({"14": "yet another thing"})
    col.update({'_id': my_str}, my_doc)
else:
    # Insert the new document with all the new attributes
    col.insert({'_id': my_str, 'hours': [{"14": "yet another thing"}]})

相关问题 更多 >