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.
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.
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.
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" }