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

浏览:46日期:2023-07-17

问题描述

{ '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=2 的 text 的内容,又该如何写呢?

问题解答

回答1:

这个可以使用mongodb的数组定位器,详细:http://www.co-ding.com/?p=274

回答2:

从mongodb命令行可以这样删除(pymongo基本上格式一样了,没测试):

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

更新的话 写起来貌似就没有这么直白了,for遍历一下吧。。//或者是先删了再添加进去?这样顺序可能不满足要求了。。

相关文章: