skip to Main Content

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"??

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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"]}});
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search