Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
638 views
in Technique[技术] by (71.8m points)

pymongo 含有子条件的操作 应该怎么写?

mongodb pymongo:
有两条记录是这样

{"a":"AAA" , "b":[ {"b11": "b11value" ,"b12":"b12value"} , { "b21":"b21value" , "b22":"b22value" } ]}

{"a":"BBB" , "b":[ {"b11": "b11value" ,"b12":"b12value"} , { "b21":"b21value" , "b22":"b22value" } ]}

我想更新a为AAA且b中b11的值为b11value的值为b11111111value:
结果应该是这样:

{"a":"AAA" , "b":[ {"b11": "b11111111value" ,"b12":"b12value"} , { "b21":"b21value" , "b22":"b22value" } ]}

{"a":"BBB" , "b":[ {"b11": "b11value" ,"b12":"b12value"} , { "b21":"b21value" , "b22":"b22value" } ]}

以及把a为AAA且b中b11的值为b11value的(b11删除)
结果应该是这样:

{"a":"AAA" , "b":[ { "b21":"b21value" , "b22":"b22value" } ]}

{"a":"BBB" , "b":[ {"b11": "b11value" ,"b12":"b12value"} , { "b21":"b21value" , "b22":"b22value" } ]}

一个更新,一个是删除
这两个怎么写?
sql语句应该怎么写?谢谢


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

例子里c为你的集合名。

第一个:

db.c.update(
    {'a': 'AAA', 'b': {'$elemMatch': {'b11': 'b11value'}}}, 
    {'$set': {'b.$.b11': 'b11111111value'}})

第二个:

db.c.update(
    {'a':'AAA'}, 
    {'$pull': {'b': {'b11': 'b11111111value'}}})

用到了$elemMatch,$set,$pull三个修改器。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...