In MongoDB, I could store a boolean like so:
active: True
But that doesn't really take advantage of NoSQL, since there's no reason to have the active property at all if it's false. Is there a way to have a property with whose only characteristic is being set or unset? A property without a value, or perhaps something else?
Best Answer
MongoDB's dynamic schema supports different fields for documents within the same collection, so there is no strict requirement for all documents to have an
active
field. The main consideration here will be how that affects your application logic; it may be simpler to have an explicit field present and check the value.If you have an index on a field, documents that do not have that field present will have a
null
value included in the index by default. This can potentially be useful if you want to save some bytes of storage by assuming that missing values arefalse
.If it only makes sense to store a
true
value for your use case (and you do not want to search onfalse
values), you can:$set
theactive
field to indicatetrue
values$unset
theactive
field to indicatefalse
valuesIf you need to query on both
true
andfalse
values ofactive
, you would be better using a normal (non-sparse) index.Notes:
You can use the
$exists
operator to match documents where a field does (or does not) exist.FAQ: How do I query for fields that have
null
values?