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:
- Insert a document with a
null
parent field:
{
"_id": 1,
"position": null
}
- Attempt to add or update a nested field using dot notation:
db.collection.updateOne(
{ "_id": 1 },
{ "$set": { "position. coordinates": "new value" } }
)
- 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?