1

How do I create a document if it doesn't exist with MongoDB?

if(db.collection.find({_id: _id}) == null) {
  db.collection.insertOne({_id: _id});
}

Thats the logic of what i'm thinking.

Nathan O
  • 72
  • 9
  • 1
    Possible duplicate of [insert if nonexistent, but do not update](http://stackoverflow.com/questions/16358857/mongodb-atomic-findorcreate-findone-insert-if-nonexistent-but-do-not-update) – adeneo Mar 01 '16 at 02:43
  • @adeneo I have tried that but I get the error `MongoError: need remove or update` – Nathan O Mar 01 '16 at 03:04

2 Answers2

8

You can do this atomically with an empty upsert:

db.collection.update({_id: _id}, {}, {upsert: true});

If a document with a matching _id already exists the update will be a no-op, otherwise a document will be created.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
-1

Please try this one

> var _id = 'the-black-horse-london-pub-san-francisco';
> if (db.users.find({_id: _id}).count() == 0) {db.users.insert({_id: _id})}
> db.users.find({})
  { "_id" : "the-black-horse-london-pub-san-francisco" }
zangw
  • 43,869
  • 19
  • 177
  • 214
  • The if statement I put in my question was just pseudo code and doesn't work, and I'm not trying to make a new `ObjectId()`; I'm just trying to find an _id or any parameter. – Nathan O Mar 01 '16 at 03:15
  • Its just a string an example is `the-black-horse-london-pub-san-francisco` – Nathan O Mar 01 '16 at 03:21
  • @NathanO, I have updated my answer, the correct way could be done through check the `cousor.count()`. since the `find` return cursors... – zangw Mar 01 '16 at 03:29