1

I am new to mongo and I am hoping you can help me with a novice question

I am trying to achieve this functionality in one query by fetching for something arbitrary like an id:

If no found results, then insert, else just return found results

Is this possible for insert-batch as well? Where if no found results for one of the inserting array elements, then insert, else return that element along with the others in the array.

Everywhere I have looked so far recommend either upsert (which achieves something different) or findAndModify (which I am not sure is overkill or not) MongoDB atomic "findOrCreate": findOne, insert if nonexistent, but do not update

I am very grateful for help you can offer.

All the best,

Ben

Community
  • 1
  • 1
Benjamin McFerren
  • 822
  • 5
  • 21
  • 36
  • whats wrong with db.collection.update() and/or db.collection.save()? – VedantK Nov 18 '15 at 06:53
  • 3
    Possible duplicate of [MongoDB atomic "findOrCreate": findOne, insert if nonexistent, but do not update](http://stackoverflow.com/questions/16358857/mongodb-atomic-findorcreate-findone-insert-if-nonexistent-but-do-not-update). Yes this is what `findAndModify()` does. If you want to "always" update then use `$set` instead of `$setOnInsert`. – Blakes Seven Nov 18 '15 at 06:54

1 Answers1

0

According to description mentioned above as a solution to it use findAndModify mongo shell method

It will modify document and return modified document with upsert as argument which when true inserts a new document into mongo collection if no match found otherwise it will perform update operation on document if match found

findAndModify also accepts new as argument which when true returns modified document if match is found or original document when new set to false otherwise it returns inserted document if no match found.

For more detailed description regarding findAndModify method please refer the documentation in following URL

https://docs.mongodb.org/manual/reference/method/db.collection.findAndModify/

Rubin Porwal
  • 3,736
  • 1
  • 23
  • 26