_INT1
(알리오 (이창호) 검색(Int))
1
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?
steevej
(Steeve Juneau)
2
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.
steevej
(Steeve Juneau)
3
@_INT1, more that 2 weeks ago I provided you with some alternative ways to solve your issue.
I would appreciate a followup.
Thanks in advance.