5

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?

4 Answers 4

14

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

On supported (later) versions on MongoDB:

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.