26

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

Talha Awan
  • 4,573
  • 4
  • 25
  • 40
f1nn
  • 6,989
  • 24
  • 69
  • 92

1 Answers1

24

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 ] }
Gianfranco P.
  • 10,049
  • 6
  • 51
  • 68
  • thats good, thanks, but I actually have no idea what to place as a 'selector'. The best way will be smth like "instrument:[...]", but I don't know what is the current value of "instrument". – f1nn Oct 22 '12 at 13:27
  • 2
    your _selector_ is `{ "instruments" : { $exists : true } }` and the _document_ is what you want to update it to, for example `$set` something or `$push` to append an element to an array – Gianfranco P. Oct 22 '12 at 15:29
  • 1
    I just want to use the unique key I've defined on the table to determine update v.s. insert. I don't want to have to specify it again in the selector parameter. Is there a way to do that? – sming Jul 29 '14 at 10:14
  • If upsert is true and there are documents that match the query criteria, update() performs an update. See the behaviour http://docs.mongodb.org/manual/reference/method/db.collection.update/#upsert-option - I believe this is better than manually coding this in your application – Gianfranco P. Dec 20 '14 at 17:51