Alon1980
Alon1980

Reputation: 1267

Which is better for Mongo: empty field or no field at all?

In MongoDb - in case i have fields that are not always contain values - which is better practice: keep same fields in all records even if sometimes those fields are empty or not create those field at all?

10x!

Upvotes: 6

Views: 1343

Answers (2)

Sammaye
Sammaye

Reputation: 43884

It depends.

Do you need those fields later? If so then their creation and subsequent usage could result in fragmentation, whereas pre-allocating the fields with a null or default value will help prevent such scenarios.

It is true that field names can occupy a 3rd of the documents disk space due to lack of compression in the current versions of MongoDB (it has been noted this is to change soon), however, sometimes this is over stated. If the difference is one field then it might be no more than a couple of bytes and even though some may say you will notice...you won't in reality when you have a real data set in there.

Upvotes: 0

Maxim Krizhanovsky
Maxim Krizhanovsky

Reputation: 26699

The fields will occupy disk space for the key, even if there is no value, so better do not include them; unless you need to find what documents does not contain such field / contain empty field

MongoDB is schemaless and each document in the collection can have different fields, as long as that makes sense for your application.

Upvotes: 4

Related Questions