Herodot Thukydides
Herodot Thukydides

Reputation: 147

MongoDb Best Practice | Insert "null" fields

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
}]

Upvotes: 4

Views: 4877

Answers (1)

D. SM
D. SM

Reputation: 14480

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.

Upvotes: 6

Related Questions