4

Hello I am new to MongoDB and i have been looking for a way to add a field to a embedded document in an array

// collection

> db.test.find().pretty();
{
    "_id" : ObjectId("5761765a31356152793c8790"),
    "name" : "bb",
    "email" : "bb@mail",
    "projects" : [
        {
            "project_id" : ObjectId("576179bf31356152793c879c")
             //How can i add a name here
        }
    ]
}
> 
4
  • You want to add same name for both project_id? or specific name for each? Commented Jun 15, 2016 at 16:12
  • a different name i just want to be able to access the projects.project_id Commented Jun 15, 2016 at 16:14
  • Can you not just do $set: {"projects.0.name": "foo"}? Commented Jun 15, 2016 at 19:32
  • @slugonamission I tried this db.test.update({name:'bb'},{$set :{projects.0.name:'foo'}}) and it gives me this error SyntaxError: Unexpected number Commented Jun 16, 2016 at 8:34

1 Answer 1

6

Figured it out :) db.test.update({projects:{$elemMatch:{"project_id" : ObjectId("576179bf31356152793c879c")}}},{$set :{'projects.$.name':'foo'}},true); Hope it helps someone Thank you !

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

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.