{
id: 1,
name: "venkat",
description: "Description",
address: "chennai",
pinCode: "600100",
authenticationCode: "123",
authenticated: false,
deleted: false,
Location: [
{
name: "foo",
description: "LocationDecription",
parent: "parent",
UserAccess: [
{
loginName: "paklon",
role: "role"
}
]
}
]
}
I need to update role:"admin"
where conditions match like id: 1
, Location
's array name: "foo"
and Location
nested array of "UserAccess.loginName": "paklon"
and then update the role.
According to above mentioned description as a solution to it please try executing following update operation in MongoDB shell
db.collection.update({
"id": 1,
"Location": {
$elemMatch: {
"name": "foo",
"UserAccess": {
$elemMatch: {
"loginName": "paklon"
}
}
}
}
}, {
$set: {
"Location.$.UserAccess.0.role": "admin"
}
})
The following query should work:
db.collection.update(
{"id": 1, "Location.name": "foo", "Location.UserAccess.loginName": "paklon"},
{$set: {"Location.0.UserAccess.0.role": "admin"}}
)
To update a particular element in an array you need to use positional operator "$" that actually a placeholder for the first element. So it could be replaced with "0" and as it permitted using the "$" only once in the query, you will have to use "0" at the end of the query in any case.
Also take a look at a corresponding mongodb documentation