How to delete nested object from MongoDB collection

Sometimes, we write data into our mongodb collection by accident.

I can share interesting case that happened not so long ago.

My colleague passed id that has .(dot) in it to my API. Then on the backend mongodb saved the id. But when it saved the id, because of the dot, it got saved in the nested way. Ex: GET /api/bar?fooId=xyz.abc.123

So, this is what I can see in the database:

xyz

abc

123

Meanwhile other records are just stored like 456, or 555 or 123. Means as a single entry.

And this is an issue, because when we try to retrieve the data, nested object cannot be properly mapped back to model that I pass to fronted. The whole controller stops working, because of one invalid record that fails to be mapped properly.

That’s why you should:

  1. Validate the id
  2. Or clean up the id

So, in order to make the API work again, I needed to delete the invalid record from DB. This is how it can be done from mongodb terminal

db.getCollection('a.bcd').update({foo:"bar",_id:ObjectId("XXX")},{$unset:{"xyz.abc":""}},{ multi: true })

Note that your collection can be sharded, so you need to specify, your shard key in the first part of the update. For example, in my case shard key is foo.

The code above will delete the xyz

Hope, this saves time for someone and will be useful.

So, the lesson is, always validate the inputs )

Leave a Reply

Your email address will not be published. Required fields are marked *