node.js - MongoDB atomic "findOrCreate": findOne, insert if nonexistent, but do not update -
as title says, want perform find (one) document, _id, , if doesn't exist, have created, whether found or created, have returned in callback.
i don't want update if exists, i've read findandmodify does. have seen many other questions on stackoverflow regarding again, don't wish update anything.
i unsure if creating (of not existing), update talking about, it's confuzzling :(
beginning mongodb 2.4, it's no longer necessary rely on unique index (or other workaround) atomic findorcreate operations.
this the $setoninsert operator new 2.4, allows specify updates should happen when inserting documents.
this, combined upsert option, means can use findandmodify achieve atomic findorcreate-like operation.
db.collection.findandmodify({ query: { _id: "some potentially existing id" }, update: { $setoninsert: { foo: "bar" } }, new: true, // return new doc if 1 upserted upsert: true // insert document if not exist }) as $setoninsert affects documents being inserted, if existing document found, no modification occur. if no document exists, upsert 1 specified _id, perform insert set. in both cases, document returned.
Comments
Post a Comment