NodeJS + Mongo: Insert if not exists, otherwise - update

丶灬走出姿态 提交于 2019-12-23 06:49:08

问题


I have an object in my mongodb collection. Its schema is:

{
    "instruments": ["A", "B", "C"],
    "_id": {
        "$oid": "508510cd6461cc5f61000001"
    }
}

My collection may have such object, but may not. I need to check if object with key "instruments" exists (please, notе, I don't know what value "instrument" is at this time, it may contain any value or an array), and if exists - perform update, otherwise – insert a new value. How can I do this?

collection.find( {  "instruments" : { $exists : true } }, function(err, object){
    if (object) {
        //update
    } else {
        //insert
    }
});

doesn't work ((


回答1:


If you want to insert one document if it is not found, you can use the upsert option in the update() method:

collection.update(_query_, _update_, { upsert: true });

See docs for the upsert behavior.

An example with the $exists operator.

Let's say you have 6 documents in your collection:

> db.test.find()
{ "_id": ObjectId("5495aebff83774152e9ea6b2"), "a": 1 }
{ "_id": ObjectId("5495aec2f83774152e9ea6b3"), "a": [ ] }
{ "_id": ObjectId("5495aec7f83774152e9ea6b4"), "a": [ "b" ] }
{ "_id": ObjectId("5495aecdf83774152e9ea6b5"), "a": [ null ] }
{ "_id": ObjectId("5495aed5f83774152e9ea6b7"), "a": [ 0 ] }
{ "_id": ObjectId("5495af60f83774152e9ea6b9"), "b": 2 }

and you want to find documents that have a certain field "a"), you can use find() method with the $exists operator (node docs). Note: this will also return documents which field is an empty array.

> db.test.find( { a: { $exists: true } } )
{ "_id": ObjectId("5495aebff83774152e9ea6b2"), "a": 1 }
{ "_id": ObjectId("5495aec2f83774152e9ea6b3"), "a": [ ] }
{ "_id": ObjectId("5495aec7f83774152e9ea6b4"), "a": [ "b" ] }
{ "_id": ObjectId("5495aecdf83774152e9ea6b5"), "a": [ null ] }
{ "_id": ObjectId("5495aed5f83774152e9ea6b7"), "a": [ 0 ] }


来源:https://stackoverflow.com/questions/13010290/nodejs-mongo-insert-if-not-exists-otherwise-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!