Home:ALL Converter>Retrieve empty array or null in mongoDB documents

Retrieve empty array or null in mongoDB documents

Ask Time:2018-03-05T06:10:06         Author:Ernesto_Che

Json Formatter

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?

Author:Ernesto_Che,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/49101017/retrieve-empty-array-or-null-in-mongodb-documents
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
yy