MongoDB Booleans

mongodbnosql

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 are false.

If it only makes sense to store a true value for your use case (and you do not want to search on false values), you can:

  • $set the active field to indicate true values
  • $unset the active field to indicate false values
  • use a sparse index so only the documents with a value present are indexed

If you need to query on both true and false values of active, you would be better using a normal (non-sparse) index.

Notes:

Related Question