MongoDB Delete documents that don't have given field
Asked Answered
R

4

18

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

Rhigolene answered 17/6, 2016 at 10:30 Comment(0)
S
19

Use the $exists operator in combination with the $or operator within your remove query:

db.users.remove({
    "$or": [
        { "firstName": { "$exists": false } },
        { "lastName": { "$exists": false } }
    ]
})
Skateboard answered 17/6, 2016 at 10:39 Comment(0)
A
11

You can use the $exists operator with two subsequent calls:

db.users.remove({firstName: { $exists: false } })
db.users.remove({lastName: { $exists: false } })
Anguiano answered 14/12, 2020 at 22:36 Comment(1)
This is good, however you can drop the quote marks all together for this scenario.Hornback
L
2

Try this:

db.users.remove({
    $or: [
       { firstName: { $exists: false } },
       { lastName: { $exists: false } }
    ] 
});
Lisandralisbeth answered 17/6, 2016 at 10:41 Comment(0)
A
0
db.getCollection('collectionName').deleteMany({
    "field1":{$exists:false},
    "field2":{$exists:false},
    "field3":{$exists:true}
    })
Apparent answered 3/8, 2023 at 5:15 Comment(1)
Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community?Enrobe

© 2022 - 2024 — McMap. All rights reserved.