Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

88
Views
Update nested document with mutiple conditions
{
    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.

9 months ago · Santiago Trujillo
2 answers
Answer question

0

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"
    }
})
9 months ago · Santiago Trujillo Report

0

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

9 months ago · Santiago Trujillo Report
Answer question
Find remote jobs