Storing null vs not storing the key at all in MongoDB

Zaid Masud picture Zaid Masud · Sep 13, 2012 · Viewed 30.9k times · Source

It seems to me that when you are creating a Mongo document and have a field {key: value} which is sometimes not going to have a value, you have two options:

  1. Write {key: null} i.e. write null value in the field
  2. Don't store the key in that document at all

Both options are easily queryable, in one you query for {key : null} and the other you query for {key : {$exists : false}}.

I can't really think of any differences between the two options that would have any impact in an application scenario (except that option 2 has slightly less storage).

Can anyone tell me if there are any reasons one would prefer either of the two approaches over the other, and why?

EDIT

After asking the question it also occurred to me that indexes may behave differently in the two cases i.e. a sparse index can be created for option 2.

Answer

Aurélien B picture Aurélien B · Sep 13, 2012

Indeed you have also a third possibility : key: "" (empty value)

And you forget a specificity about null value. Query on key: null will retrieve you all document where key is null or where key doesn't exist.

When a query on $exists:false will retrieve only doc where field key doesn't exist.

To go back to your exact question it depends of you queries and what data represent. If you need to keep that, by example, a user set a value then unset it, you should keep the field as null or empty. If you dont need, you may remove this field.