update and set field if it's blank or not set

3,780 views
Skip to first unread message

rl

unread,
Mar 28, 2012, 11:32:40 PM3/28/12
to mongod...@googlegroups.com
I have an update that sets a few fields on several hundred records (out of millions) based on some criteria.  However, there is one field that I want to only set if it's not set.  e.g.  I have a URL field.  If there is no URL, I want to force it to be "http://www.mycompany.com" but if that field already has a value, I want to keep it.  I need an example of how to do this.

Thanks in advance!

H.J

unread,
Mar 29, 2012, 12:55:35 AM3/29/12
to mongod...@googlegroups.com
eg:

db.t8.insert({"_id":1,"other":"apple","url":"http://www.mongodb.org"})
db.t8.insert({"_id":2,"other":"apple","url":null})
db.t8.insert({"_id":3,"other":"apple","other":"apple"})

If in all doc there are the 'url' field then you can use:

db.t8.update({$or:[{"url":null},{"url":{$exists:false}}]},
{$set:{"url":"http://www.mycompany.com"}})

if in some doc this field doesn't exist, then you can use:

db.t8.find({$or:[{"url":null},{"url":{$exists:false}}]}).forEach(function(doc){
doc.url = "http://www.mycompany.com";
db.t8.save(doc);
})

Hope this help.

2012/3/29 rl <rob...@cloud2market.com>:

> --
> You received this message because you are subscribed to the Google Groups
> "mongodb-user" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/mongodb-user/-/s_aZnKbr2ucJ.
> To post to this group, send email to mongod...@googlegroups.com.
> To unsubscribe from this group, send email to
> mongodb-user...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/mongodb-user?hl=en.

--
尽人事,听天命!

Reply all
Reply to author
Forward
0 new messages