Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove column from child collection

Tags:

unset

mongodb

I have a collection in MongoDB called CrawlUser. It has a list called CrawlStatuses, which is a list of CrawlStatus objects. CrawlStatus has a property called LastErrorMessage which I want to remove from the collections.

I tried to do the following to remove it but it didn't work... No error message given, but the LastErrorMessage column is still there.

db.CrawlUser.update( {}, { $unset: { "CrawlStatuses.LastErrorMessage": 1 } }, false, true);

Any ideas what I'm doing wrong?

One other related question, if I do the $unset command on a column in a collection that is very large (millions of rows), mongodb uses up all of the ram on the server (as if it's trying to store the entire collection in memory), then the server crashes. Is there a better way to remove columns when you have large collections?

like image 536
Justin Avatar asked Feb 13 '11 22:02

Justin


People also ask

How do I delete all files in a collection?

To delete all documents in a collection, pass an empty document ( {} ). Optional. To limit the deletion to just one document, set to true . Omit to use the default value of false and delete all documents matching the deletion criteria.


1 Answers

The update with the empty parameter doesn't seem to work. I tried it in the mongo shell and mongoconsole. In the mongoconsole it gave an error about update expecting the first parameter to be an array or an object.

However, you can do the same thing using the $exists find query.

Try:

`db.CrawlUser.update( {CrawlStatuses:{$exists:true}}, { $unset: { "CrawlStatuses.LastErrorMessage": 1 } }, false, true);`

That worked for me.

Keep in mind that based on the docs, $exists doesn't use an index, so it will be slower. I suggest adding a parameter that you can add an index on and query it when doing the $unset.

like image 197
Alexandru Petrescu Avatar answered Sep 18 '22 12:09

Alexandru Petrescu