Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb Best Practice | Insert "null" fields

Tags:

mongodb

I have a question regarding best practices to insert Documents in MongoDb.

In my data source the key "myData2" can be null or a string. Should I add "myData2" as null to my database or is it better to leave the value out if not defined? What is the "clean" way to deal with this?

[{
   "myData1": "Stuff",
   "myData2": null
}]
like image 421
Herodot Thukydides Avatar asked Oct 25 '25 08:10

Herodot Thukydides


1 Answers

Since MongoDB permits fields to be added to documents at any time, most (production) applications are written to handle both of the following cases:

  • A new field is added to the code, but the existing data doesn't have it, and it needs to be added over time to the existing data either on demand or as a background process
  • A field is no longer used by the code but still contains values in the database

What would your application do if the field is missing, as opposed to if it's set to the null value? If it would do the same thing, then I suggest not setting fields to null values for two reasons:

  1. It streamlines the code because you only need to handle one possibility (missing field) on the reading side, instead of two (field missing or null)
  2. It requires less storage space in the database.
like image 140
D. SM Avatar answered Oct 28 '25 02:10

D. SM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!