Ernesto_Che
Ernesto_Che

Reputation: 77

Retrieve empty array or null in mongoDB documents

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

Answers (4)

Praveen Kumar Verma
Praveen Kumar Verma

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

Mark Simon
Mark Simon

Reputation: 762

On supported (later) versions on MongoDB:

find({field:{$not:{$size: 0}}})

Upvotes: 0

Lincoln
Lincoln

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

JohnnyHK
JohnnyHK

Reputation: 312149

You can use the $in operator to query for docs where a field's value is any of a list of target values:

db.students.find({sports: {$in: [null, []]}})

Note that the null case also matches docs where the field isn't present.

Upvotes: 14

Related Questions