I'm trying to atomically insert an empty document if the capped collection is empty or return the last naturally sorted document if not empty. Can I do this with findAndModify?
db.collection.findAndModify({
query: { _id: { $exists: true }},
sort: { $natural: -1 },
update: {},
upsert: true,
new: true
});
I would have expected this to either return the latest document (if the collection is non empty) or insert a new document if none exist, however, it inserts a blank document (without an _id) every single time it's called. Does findAndModify work with capped collections? I need the added document to have an _id
.
Thanks.
-Scott