mongodb更新匹配的文档失败 [英] mongodb update matched doc fail

查看:154
本文介绍了mongodb更新匹配的文档失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

mongoimport导入了10000个文档,_id为6个长度的随机字符串

There are 10000 docs import by mongoimport, the _id is 6 length random string

{_id:"xxxxxx","u":0,"t":0}

因为mongoimport无法指定数据类型,所以将像"123456"这样的字符串作为int类型导入. 因此,我手动删除了原件并将其重新插入为

because mongoimport can not specifiy data type, so string like "123456" was imported as type int. So I manually delete originals and re-insert them as

db.xxx.insert({_id:"123456","u":0,"t":0})

因为默认类型0为Double,所以我将其更改为int方式:

Because the default type of 0 is Double, so I change them to int by:

db.xxx.update({},{$set:{u:NumberInt(0)}},false,true)
WriteResult({ "nMatched" : 100000, "nUpserted" : 0, "nModified" : 99994 })

似乎6个文档更改失败,我通过以下方法验证更改:

Seems 6 docs change failed, I validate the change by:

> db.code.find({u:{$type:1}})
{ "_id" : "263798", "t" : 4, "u" : 0 }
{ "_id" : "375249", "t" : 7, "u" : 0 }
{ "_id" : "659472", "t" : 3, "u" : 0 }
{ "_id" : "672534", "t" : 3, "u" : 0 }
{ "_id" : "784392", "t" : 0, "u" : 0 }
{ "_id" : "875631", "t" : 0, "u" : 0 }

此更新仅修改了mongoimport导入的文档,但不包括我手动插入的文档,为什么?

the update only modify docs which was imported by mongoimport but leave alone docs which I manually insert, why?

推荐答案

这不是失败,而是设计使然.

It's not a failure but by design.

批量操作API 下,如果您提供要更新的值与文档的现有值匹配的文档,则不会将其标记为已修改,并且实际上不会进行任何重写文档的尝试.

Under the Bulk Operations API, if you supply a value to update that matches an existing value of the document then it is not marked as modified and actually does not make any attempt to re-write the document.

简单测试:

db.junk.insert({ "a": 1 })
WriteResult({ "nInserted" : 1 })

db.junk.update({ "a": 1},{ "$set": { "a": 2 }})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

db.junk.update({ "a": 2 },{ "$set": { "a": 2 }})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })

db.junk.update({ "a": 2 },{ "$set": { "a": NumberInt(2) }})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

db.junk.update({ },{ "$set": { "a": NumberInt(2) }})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })

从2.6版开始,MongoDB Shell中的所有操作实际上都使用批量操作API .在这里,您可以看到来自该API的 WriteResult 这正在发生.

All operations in the MongoDB shell as of version 2.6 are actually using the Bulk Operations API. This is where you see the WriteResult which comes from that API as proof this is happening.

因此,这里的简短情况是,如果您手动插入"了要修改的正确类型的项目,则它们不会被更改.

So the short case here is if you have "manually inserted" items that are of the correct type you are modifying to, then they do not get changed.

这篇关于mongodb更新匹配的文档失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆