Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
642 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 Reply

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三个修改器。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...