Mongo update array of nested dict in Django
I'm trying to update a data but I'm facing the issue because it's nested form
some fields are already present in the database I have fetched them and stored them in the DF variable
the existing data structure looks like this
{
"created_by_id":122,
"updated_by_id":123,
"farm_area": [
{
"area_id": 1,
"area_name": "Area 1",
"area_acerage": 4,
"zone_latest_id": 1,
"zone_name": "test zone",
"zone_acerage": 2,
"area_zone":[
{
"zone_acerage":0.3
}
]
"device_info":[
{ "device_id":232,
"device_type":"sensor"
}
]
},
{
"area_id": 2,
"area_name": "Area 2",
"area_acerage": 4,
"area_structure_type": "polyhouse"
}
]
}
and I am trying this existing data by sending new data which
{
"created_by_id":122,
"updated_by_id":123,
"farm_area": [
{
"area_id": 1,
"area_name": "Area 1",
"area_acerage": 4,
"zone_latest_id": 1,
"zone_name": "test zone",
"zone_acerage": 2,
"area_zone":[
{
"zone_acerage":0.3
}
]
"device_info":[
{ "device_id":232,
"device_type":"sensor"
}
]
},
{
"area_id": 2,
"area_name": "Area 2",
"area_acerage": 4,
"area_structure_type": "polyhouse",
"area_zone":[
{
"zone_acerage":0.3,
"zone_name":"Test Zone"
}
]
"device_info":[
{ "device_id":232,
"device_type":"sensor"
}
]
}
]
}
But every time I run this command
collection.update_one({"_id": ObjectId(str(kwargs['pk']))}, {"$set": request.data}, upsert=True)
The data is getting replaced by the new one and due to this I'm losing some of my columns from the database But I'm looking for the output in which both of them are merged so that I wouldn't lose any column and the structure remains the same
I anyone can help I am using Django and MongoDB
Here's one way to update
it using "arrayFilters"
.
N.B.: You can replace "_id"
and new data programmatically.
db.collection.update({
"_id": ObjectId("5a934e000102030405000000")
},
{
"$set": {
"farm_area.$[elem].area_zone": [
{
"zone_acerage": 0.3,
"zone_name": "Test Zone"
}
],
"farm_area.$[elem].device_info": [
{
"device_id": 232,
"device_type": "sensor"
}
]
}
},
{
"arrayFilters": [
{
"elem.area_id": 2
}
]
})
Try it on mongoplayground.net.