Storing null vs not storing the key at all in MongoDB Storing null vs not storing the key at all in MongoDB mongodb mongodb

Storing null vs not storing the key at all in MongoDB


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.


Note that, since MongoDB doesnt use field name dictionary compression, field:null consumes disk space and RAM, while storing no key at all doesnt consume resources.


It really comes down to:

  • Your scenario
  • Your querying manner
  • Your index needs
  • Your language

I personally have chosen to store null keys. It makes it much easier to integrate into my app. I use PHP with Active Record and uisng null values makes my life a lot easier since I am not having to put the stress of field depedancy upon the app. Also I do not need to make any complex code to deal with magics to set non-existant variables.

I personally would not store an empty value like "" since if your not careful you could have two empty values null and "" and then you'll have a hap-hazard time of querying specifically. So I personally prefer null for empty values.

As for space and index: it depends on how many rows might not have this colum but I doubt you will really notice the index size increase due to a few extra docs with null in. I mean the difference in storage is mineute especially if the corresponding key name is small as well. That goes for large setups too.

I am quite frankly unsure of the index usage between $exists and null however null could be a more standardised method by which to query the existance since remember that MongoDB is schemaless which means you have no requirement to have that field in the doc which again produces two empty values: non-existant and null. So better to choose one or the other.

I choose null.