pvgdev
pvgdev

Reputation: 157

Delete documents where value is not an array

It seems that mongodb allows the same syntax for deleting documents where the value is a single value, and whenever the value is present in a collection:

This

db.SomeCollection.deleteMany({UserId: 12345});

Can affect both {UserId: 12345} and {UserId: [12345, 67895, 87897]}.

I understand that this schema isn't ideal; we are using a singular UserId prop to denote both a single id int, and an array of ints. However, I've inherited a database that makes use of mongodb's dynamic nature, if you catch my drift.

What is the safest way to execute a deleteMany query, specifying I only want to delete documents where the value is a single integer?

Upvotes: 1

Views: 670

Answers (1)

mickl
mickl

Reputation: 49945

You can use $type operator to check field type but it's not so obvious in this case. You can't check if UserId is of type double because MongoDB will indicate that array of doubles is a double as well (more here). So you need to invert your logic and check if documents you're trying to remove are not an array (type 4):

db.SomeCollection.deleteMany({ $and: [ { UserId: 12345 }, { UserId: { $not: { $type: 4 } } } ] })

Upvotes: 1

Related Questions