Storing null vs not storing the key at all in MongoDB
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.
Another point you might want to consider is when you use OGM tools like Hibernate OGM.
If you are using Java, Hibernate OGM supports the JPA standard. So if you can write a JPQL query, you would be theoretically easy if you want to switch to an alternate NoSQL datastore which is supported by the OGM tool.
JPA does not define a equivalent for $exists in Mongo. So if you have optional attributes in your collection then you cannot write a proper JPQL for the same. In such a case, if the attribute's value is stored as NULL, then it is still possible to write a valid JPQL query like below.
SELECT p FROM pppoe p where p.logout IS null;
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
.
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.