1

Situation:

I have a collection named 'employees'. This collection contains an array of managers. Each manager object has a property called 'directReports'. This property is an array of objects representing their subordinates. For example:

 db.employees.find({ name: 'John Smith' });

{
   "id" : 1234,
   "name" : "John Smith",
   "FirstName" : "John",
   "LastName" : "Smith",
   "SamAccountName" : "jsmith",
   "DepartmentName" : "Management",
   "SupID" : 0,
   "Email" : "[email protected]",
   "SupSamAccountName" : "bross",
   "SupName" : "Bob Ross",
   "directReports" : [
    {
        "id" : 5678,
        "name" : "Jane Doe",
        "FirstName" : "Jane",
        "LastName" : "Doe",
        "SamAccountName" : "jdoe",
        "DepartmentName" : "Agent",
        "SupID" : 1234,
        "Email" : "[email protected]",
        "SupSamAccountName" : "jsmith",
        "SupName" : "John Smith",
    },...]}

What I'd Like to Do:

I'd like to add a new property called 'status' (with a value of 'Lunch') to Jane Doe.

How can I do this?

Any help is extremely appreciated!

2 Answers 2

1

Assuming SamAccountNames are unique:

db.employees.update({
    { SamAccountName: "jsmith", directReports.SamAccountName: "jdoe" },
    { $set: { directReports.$.status: "Lunch" } }
})

Based on this question's tags, since you're using Mongoose, be sure to update your schema appropriately. You might consider reworking your schema to take advantage of Mongoose query population.

Sign up to request clarification or add additional context in comments.

5 Comments

I tried running this and it gave me a syntax error: E QUERY [thread1] SyntaxError: invalid property id @(shell)
Are you using ids or _ids? I assumed id based on your question. By default MongoDB uses _id as the unique identifier, which are ObjectIds
I'm actually using the SamAccountName for both the manager and subordinate. I tried even using Mongo's _id but that didn't work either.
How about this: is SamAccountName unique across all employees?
0

I think you need to add 'status' with the value of 'launch' to your model and after create a function to update all the employees data. Hope it helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.