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?
JohnnyHK :
You can use the $in operator to query for docs where a field's value is any of a list of target values:\n\ndb.students.find({sports: {$in: [null, []]}})\n\n\nNote that the null case also matches docs where the field isn't present.",
2018-03-04T23:57:02
Lincoln :
I believe you can use $elemMatch for this:\n\ndb.students.find({ $not: { $elemMatch: { $exists: true } } })\n\n\nThis tells mongoDB to fail if the array exists and has values. It only returns values that are null or empty.",
2019-08-13T17:48:41