How to compare two properties in MongoDB, I want to find and delete all those rows where "income per annum" is greater than "savings per annum"??
CodePudding user response:
You can use deleteMany. Documents that pass the filter will be deleted. For example
*$expr
is needed because we need to compare 2 fields. The query $gt
operator takes a field and a value, so here the aggregate $gt
is used with $expr
db.collection.deleteMany(
{"$expr": {"$gt": ["$income-per-annum", "$savings-per-annum"]}});
CodePudding user response:
Maybe something like this:
db.collection.find({
"$expr": {
"$gt": [
"$income",
"$savings"
]
}
}).forEach(function(doc){ db.collection.remove(_id:doc._id)})
Explained:
Find all affected documents via $expr and loop over them via forEach to remove one by one.