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

f1nn picture f1nn · Oct 22, 2012 · Viewed 30.7k times · Source

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 ((

Answer

Gianfranco P. picture Gianfranco P. · Oct 22, 2012

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 ] }