mongodb - Mongo DB Update to a sub array document -


i have structure

{         "_id" : objectid("562dfb4c595028c9r74fda67"),         "office_id" : "123456",         "employee" : [                 {                         "status" : "declined",                         "personid" : "123456",                         "updated" : numberlong("1428407042401")                 }         ] } 

this office can have multiple persons.is there way if want update employee status person under specific office_id "approved".i trying same through plain mongo java driver.what trying office id using query builder , iterate on list , save document.somewhat not satisfied iterative approach(fetch,iterate , save ) following.please suggest if there alternative way.

you can update using $ positional operator:

db.collection.update(     {         "office_id" : "123456",          "employee.status": "declined"     },      {         "$set": { "employee.$.status": "approved" }     } ); 

the positional operator saves index (0 in case above) of element array matched query. means if knew position of element beforehand (which impossible in real life case), change update statement to: {"$set": {"employee.0.status": "approved"}}.

please note $ positional operator (for now) updates first relevant document only, there jira ticket this.

edit:

using java driver, above update may done (untested):

basicdbobject update = new basicdbobject(); basicdbobject query = new basicdbobject(); query.put("office_id", "123456"); query.put("employee.status", "declined");  basicdbobject set = new basicdbobject("$set", update); update.put(""employee.$.status", "approved");  collection.update(query, set); 

Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

datatable - Matlab struct computations -