3

I have a collection test with a record :

[{ number:"1524",
name:null,
cat_id:"126842"},
{number:"456",
name:null,
cat_id:null }]

How to remove the whole row having null values like this :

[{ number:"1524",
 cat_id:"126842" },
{ number:"456"}]

I tried this but whole records are getting deleted rather than just the rows.

collection.deleteMany( { $or: [{cat_id : null },{ name : null }]

Need to remove multiple variables in a single query.

MongoDB version 4.0

1 Answers1

2

In MongoDB, the $unset operator is used to delete a particular field.

You can try using the following commands to delete field that are empty

collection.updateMany({name: null}, { $unset : { name : 1 }})

This command will delete the name field from all documents where name is null. You can do a similar command for cat_id as well.

Edit : As per an answer received by me in another question I asked, You can also do the same in a single command using the following way -

collection.updateMany({
  $or : [{
    name : null
  }, {
    cat_id : null
  }]
}, [{
  $set: {
    name : { $ifNull : ["$hobby", "$$REMOVE"] },
    cat_id : { $ifNull : ["$Roll_no", "$$REMOVE"] }
  }
}]
);

However, this can only be done in MongoDb V4.2 and above. You can also look at this for another way of doing it.

Hope it helps !

Abhishek Bhagate
  • 5,583
  • 3
  • 15
  • 32