Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb - proper way to delete all elements in an array field?

Tags:

mongodb

I'm looking for the proper way to remove all elements from an array field (across all documents) in Mongodb - these appear to be equivalent, which is recommended: (or perhaps some other way?)

db.collection.update({}, { $pull : { 'myArray': {} }}, {multi:true} ) 

or

db.collection.update({}, { $set : {'myArray': [] }} , {multi:true} ) 
like image 928
UpTheCreek Avatar asked Jul 25 '13 13:07

UpTheCreek


People also ask

How do I delete everything in MongoDB?

To delete all documents that match a deletion criteria, pass a filter parameter to the deleteMany() method. The method returns a document with the status of the operation. For more information and examples, see deleteMany() .

How do I delete a specific field in MongoDB?

In MongoDB, the $unset operator is used to delete a particular field. The value specified in the $unset expression does not make any impact on the operation. The $unset has no effect when the field does not exist in the document. name of the column or field to be deleted.


1 Answers

The $set variant will be faster as the $pull will have to do calculations on arrays. I am actually not even certain whether it will work, as you're not really removing any elements with your query.

like image 58
Derick Avatar answered Sep 19 '22 16:09

Derick