Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Delete documents that don't have given field

Hello I have a beginner question I suppose... I've had a look around but could not find the answer

I have the following collection of users that I'd like to clean before I redefine my user model - how can I remove all documents that don't have the field firstname, or lastname in the following collection ?

{ "_id" : ObjectId("57615777a629d16a4c604cce"), "firstName" : "Hector", "lastName" : "yoyo", "email" : "[email protected]", "createDate" : ISODate("2016-06-15T13:26:15.900Z") }
{ "_id" : ObjectId("57615849a629d16a4c604ccf"), "firstName" : "Arnaud", "lastName" : "yaya", "email" : "[email protected]", "createDate" : ISODate("2016-06-15T13:29:45.517Z") }
{ "_id" : ObjectId("57615c33a629d16a4c604cd0"), "createDate" : ISODate("2016-06-15T13:46:27.224Z") }
{ "_id" : ObjectId("57615ff943d8b1a74c4d4216"), "createDate" : ISODate("2016-06-15T14:02:33.352Z") }

I know I can remove these one by one but I imagine there's a better solution :)

db.users.remove( { "_id" : ObjectId("57615ff943d8b1a74c4d4216") } );

Thanks

like image 697
Arnaud Bouchot Avatar asked Jun 17 '16 10:06

Arnaud Bouchot


People also ask

How do I exclude fields in MongoDB?

To exclude the _id field from the output documents of the $project stage, specify the exclusion of the _id field by setting it to 0 in the projection document.

When you remove a document from database in MongoDB remove it from disk?

FYI: MongoDB does not release disk space after you delete a document, instead, it will reuse that space for future documents, hence the storageSize being bigger than dataSize .


Video Answer


1 Answers

Alternatively, you can use the $exists operator with two subsequent calls:

db.users.remove({"firstName": { "$exists": false } })
db.users.remove({"lastName": { "$exists": false } })
like image 70
rouble Avatar answered Oct 26 '22 06:10

rouble