问题描述有如下数据:{"_id":1,"name":"dave123","favorites":["chocolate","cake","butter","apples"]}{"_id":2,"name":"li","favorites":["apples","pudding","pie","cake"]}{"_id":3,"name":"ahn","favorites":["pears","pecans","chocolate","cherries"]}{"_id":4,"name":"ty","favorites":["icecream"]}然后我刚才操作失误,原本想给数组中添加一个元素结果给添加了一个数组进去:db.test.update({_id:2},{$push:{favorites:['cake']}})执行后的数据如下:{"_id":1,"name":"dave123","favorites":["chocolate","cake","butter","apples"]}{"_id":2,"name":"li","favorites":["apples","pudding","pie","cake",["cake"]]}{"_id":3,"name":"ahn","favorites":["pears","pecans","chocolate","cherries"]}可以看到id2的文档的favorites字段中又包含了一个数组想法设法删除掉这个数组我知道$pull命令可以删除掉数组中的一个元素,但是它需要一个条件,于是问题被引到了如何在数组中查询另外一个数组.命令如下:db.tester.find({favorites:{$in:[['cake']]}})输出:{"_id":2,"name":"li","favorites":["apples","pudding","pie","cake",["cake"]]}然后我尝试使用update来完成这个操作,由于集合中就这么一条特殊数据我就没有指定条件:db.tester.update({},{$pull:{favorites:{$in:[['cake']]}}})输出:WriteResult({"nMatched":1,"nUpserted":0,"nModified":0})喜闻乐见,匹配到了东西但是没有更新东西.继续折腾在我的努力下试出来了这么一个命令:db.tester.update({favorites:{$in:[['cake']]}},{$pull:{favorites:{$in:[['cake']]}}})输出:WriteResult({"nMatched":1,"nUpserted":0,"nModified":1})这次这个数组中的元素被正确的删除掉了.最终的问题WHY?udpate操作中查询和跟随着的修改操作有什么潜在的关系吗,还是和$pull中的条件有关系?
宝慕林4294392
萧十郎
相关分类