Reputation: 77
I have a collection with all the students of my school. Each document has a sports
array property that lists the sports practiced by each student, but that property may appear either as sports: []
or sports: null
or not appear at all.
How can I retrieve all the documents that fall in one of the aforementioned three cases?
How can I add a sport to a student which only has one sport but not expressed as array, i.e. a student that has sports: "Badminton"
? Can this property become an array?
Upvotes: 5
Views: 10708
Reputation: 3510
In mongoDb filter query:
1. {field: {$size: 0}} // When find field array size is 0.
2. {field: {$not {$size: 0}}} // When find field array size is not empty.
3. {field: {$in: [null, []]}} // When field array null or empty.
Upvotes: 0
Reputation: 762
On supported (later) versions on MongoDB:
find({field:{$not:{$size: 0}}})
Upvotes: 0
Reputation: 3191
I believe you can use $elemMatch for this:
db.students.find({ $not: { $elemMatch: { $exists: true } } })
This tells mongoDB to fail if the array exists and has values. It only returns values that are null or empty.
Upvotes: 1