search

Home  >  Q&A  >  body text

mongodb - pymongo里,dict存储在list内,如何根据key-value值删除或更新该dict?

{
    "title": "hello world",
    "comments": [
                    {"id": 1, "text": "text 1"},
                    {"id": 2, "text": "text 2"},
                    {"id": 3, "text": "text 3"}, 
                    ...
                ],
    "author": "",
    "views": 1000,
}

假设我现在知道某个 comment 的 id=2,想删除 comments 中 id=2 的字典,也就是 {"id": 2, "text": "text 2"} 这条数据,应该怎样写呢?

如果是更新 id=2text 的内容,又该如何写呢?

阿神阿神2894 days ago828

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-21 11:19:36

    This can use mongodb’s array locator, details:
    http://www.co-ding.com/?p=274

    reply
    0
  • 怪我咯

    怪我咯2017-04-21 11:19:36

    You can delete it from the mongodb command line like this (pymongo basically has the same format, not tested):

    db.posts.update({'_id': xxxx}, {'$pull': { 'comments': {'id': 2} }})

    Updated, it seems that it is not so straightforward to write, so let’s go through it with for. .
    //Or delete it first and then add it? This order may not meet the requirements. .

    reply
    0
  • Cancelreply