开发者

How to replace items in MongoDB

I request JSON objects with unique ids through an API. Some of these items already exist in my MongoDB database. Is there some functionality like this:

Collection.replace({ id: '12345' }, JSON_object)

which looks for an object with that id field in the first place, and then replaces it with the new object, if it finds one, or adds a new object to the collection, if no matching object was f开发者_运维技巧ound?

I am doing this in node.js with mongoose. Unfortunatly, the ObjectId implementation seems faulty there, so I am searching for a general approach.


Remember that you must use the db.bson_serializer.ObjectID function in order to get mongodb ids.

var ObjectID = db.bson_serializer.ObjectID;
db.collection.update({_id: ObjectID('423523452')}, {foo: 'bar'}, true)


MongoDb core function update has upsert option:

db.collection.update( criteria, objNew, upsert, multi )

which will insert objNew if there is no document matching criteria. Try:

db.collection.update( { _id: ObjectID('423523452') }, JSON_object, true )

http://www.mongodb.org/display/DOCS/Updating#Updating-update%28%29

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜