Reputation: 309
I have the following object:
{
"_id" : ObjectId("5d7052a3807ab14e286ba5bd"),
"companyBases" : [
{
"vehicles" : [],
"_id" : ObjectId("5d7052a3807ab14e286ba5b0"),
"name" : "Tech Parking 3",
"location" : {
"lng" : 50.01744,
"lat" : 20.033522
},
"country" : ObjectId("5d7052a2807ab14e286ba578"),
"__v" : 0
},
{
"vehicles" : [],
"_id" : ObjectId("5d7052a3807ab14e286ba5af"),
"name" : "Tech Parking 2",
"location" : {
"lng" : 50.036017,
"lat" : 20.086752
},
"country" : ObjectId("5d7052a2807ab14e286ba578"),
"__v" : 0
}
],
"nameOfCompany" : "Transport Tech Service 2 ",
"plan" : {
"name" : "Enterprise",
"vehicles" : 56,
"companyBases" : 10,
"users" : 10,
"price" : 1200
},
"__v" : 0
}
I've tried to do something like this:
db.companies.update(
{
_id: ObjectId("5d7052a3807ab14e286ba5bd")
},
{
$push: {
"companyBases.$[filter1].vehicles": {
"name": "Truck 1",
"combustion": 28
},
"companyBases.$[filter2].vehicles": {
"name": "Truck 2",
"combustion": 28
}
}
},
{
"arrayFilters": [
{
"filter1._id": "5d7052a3807ab14e286ba5b0"
},
{
"filter2._id": "5d7052a3807ab14e286ba5af"
}
]
}
)
But, it doesn't update my nested arrays "vehicles"
It returns me:
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
I checked IDs and it's ok. I've created similar question a few days ago but with $set pipeline not $push - How to update in one query, multiple times without sharing to simple queries? , but i was thinking it's possible to rewrite that example to $push.
Upvotes: 1
Views: 71
Reputation: 3010
Issue: In array filters, the _id is matched with string instead of ObjectId
The following query would precisely update the collection:
db.companies.update(
{
_id: ObjectId("5d7052a3807ab14e286ba5bd")
},
{
$push: {
"companyBases.$[filter1].vehicles": {
"name": "Truck 1",
"combustion": 28
},
"companyBases.$[filter2].vehicles": {
"name": "Truck 2",
"combustion": 28
}
}
},
{
"arrayFilters": [{
"filter1._id": ObjectId("5d7052a3807ab14e286ba5b0")
},
{
"filter2._id": ObjectId("5d7052a3807ab14e286ba5af")
}
]
}
)
Upvotes: 3