开发者

Why did this line delete everything in my MongoDB database?

Ok, so I'm trying to roll out a small update to my site. One update includes querying upon a field that may or may not exist. This doesn't work as I want, so I decided to just make it so that the field always exists in my database. I used this line at the MongoDB shell:

> db.entries.update({Published: null},{$set: {Published: true}},false,true);

Now, I'm not fully understanding how this caused every entry object where Published is null to be deleted. I mean, it literally was deleted. I tried looking up some IDs, and .findOne will return null for them.

How does that line work? I thought it w开发者_高级运维ould take every entry where Published is null(doesn't exist), and set Published to true.


Reading about operator behavior is better than guessing operator behavior. Search for null is different from performing a check for existence.

MongoDB has a dedicated $exists operator:

http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24exists


To be honest, I'm not sure why it now works with changes, or at least, why it deleted everything with that command.

My ending command looked like this:

db.entries.update({Published: {$exists: false},$atomic: true},{$set:{"Published":true}},false,true);


I thought it would take every entry where Published is null(doesn't exist), and set Published to true.

OK, so these are two different things.

Published is null:

{ Published : null, post : 'blah' }

Published does not exist:

{ post : 'blahblah' }


You may want to post this question over at the MongoDB user group (developers check it very often) at http://groups.google.com/group/mongodb-user


Updates do not delete documents. In fact, the update you ran does what you intended, for example, if you wanted y to always have a value:

> db.foo.insert({x:1})
> db.foo.insert({x:2})
> db.foo.insert({y:null})
> db.foo.insert({y:1})
> db.foo.update({y:null},{$set : {y:true}}, false, true)
> db.foo.find()
{ "_id" : ObjectId("4db02aabbe5a5418fb65d24c"), "y" : true }
{ "_id" : ObjectId("4db02aafbe5a5418fb65d24d"), "y" : 1 }
{ "_id" : ObjectId("4db02aa1be5a5418fb65d24a"), "x" : 1, "y" : true }
{ "_id" : ObjectId("4db02aa4be5a5418fb65d24b"), "x" : 2, "y" : true }

There must have been another operation that did the delete. There might be a record of it in the logs (or there might not... it depends how long it took). It's impossible to tell from the info here what caused the deletions, but the update isn't the culprit here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜