$exists and Documents With Different Fields
You have seen that documents in one collection can have different fields. This course has a gadgets collection where this is true:
db.gadgets.find()
Output:
[
{ _id: 1, name: 'Mouse', price: 25 },
{ _id: 2, name: 'Keyboard', price: 50, discount: 10 },
{ _id: 3, name: 'Monitor', price: 220 },
{ _id: 4, name: 'Headset', price: 80, discount: 15 }
]
Two gadgets have a discount field, and two do not. The field is not null or 0 on the others. It is simply not there. To check if a field is there, use $exists:
db.gadgets.find(
{ discount: { $exists: true } },
{ _id: 0, name: 1, discount: 1 }
)
db.gadgets.find(
{ discount: { $exists: false } },
{ _id: 0, name: 1 }
)
Output:
[
{ name: 'Keyboard', discount: 10 },
{ name: 'Headset', discount: 15 }
]
[ { name: 'Mouse' }, { name: 'Monitor' } ]
$exists: true finds the documents that have the field, and $exists: false finds the ones that do not.
This flexibility is useful. When your app needs a new field, new documents can just have it. Old documents do not need to change. You saw this when you added oscars to one movie in the update lesson.
It also needs care. The database no longer keeps track of which fields exist, so your team has to. Write down what each field means. Use one name for one idea, so you do not end up with discount in some documents and disc in others. MongoDB can check the shape of documents if you turn on schema validation, but it is off by default.
In the exercise, find the discounted gadgets that cost more than 60.