I'm trying to delete a document with one operation, instead of two - countDocuments(...), deleteOne(...).
Condition: delete oldest document with user_id = xxx, if count of documents with user_id >= 5.
It's works, but it lacks document count check. I still can’t figure out how to form an aggregation pipeline for deleteOne(...), of course if possible it.
db.getCollection("collection_name").deleteOne({
$and: [
{ user_id: { $eq: '118d43cc-3f03-45a1-94f5-03a053d0b78b' } },
... ???,
{ $expr: { $min: '$created_at' } }
]
});
You can't really merge a
deleteOneoperations with an aggregation, but for this specific usecase there is a workaround.You could define a TTL index on a "new" field, then in your aggregation use
$mergeto "update" the document you want to delete by adding this TTL field.So to summarise:
x$mergeto update that document to contain fieldxThis would look similar to this: