Unable to Create or Update Nested Fields When Parent Field is null in MongoDB

Description:

When attempting to create or update nested fields using dot notation in MongoDB, if the parent field is explicitly set to null, the operation fails with an error:

sql

Cannot create field 'coordinates' in element {position: null}

This issue prevents partial updates or nested field additions in documents where parent fields are initialized as null.

Steps to Reproduce:

  1. Insert a document with a null parent field:
{
  
  
"_id": 1,
  "position": null
}
  1. Attempt to add or update a nested field using dot notation:
db.collection.updateOne(
  { "_id": 1 },
  { "$set": { "position. coordinates": "new value" } }
)
  1. MongoDB throws the following error:
Cannot create field 'coordinates' in element {position: null}

Expected Behavior:

The parent field should automatically be converted into an object (i.e., {}), allowing the nested field to be created or updated without explicit reinitialization.

How Can This Be Resolved Using Dot Notation?

Is this expected behavior documented somewhere:

Until a better answer shows up you could try:

which is not an answer to

but is a possible way to get around the limitation.

If you do not know if you are in the null vs not null situation you may create a bulkWrite with 2 ordered updateOne to cover both cases.

Alternatively, the update with aggregation syntax could be use to $set with a $cond on position:null.