mongodb - Update value mongo using Java -
i using java mongo driver db interaction. have regular updates performed on db rows , object quite nested. :
myobject:
{ _id: dbgeneratedid, myid: "a string id created", mytime: "new date()", mylist: [ { mystring: "abcdefghij", myinteger: 9000 }, { mystring: "qwertyasdf", myinteger: 9001 }, { mystring: "loremipsum", myinteger: 9002 } ] }
each update involves either adding new list item under mylist
or appending string mystring
object in each of list item. found lot of references writing/finding items , none updating items in nested object. can me this.
edit 1: helpful if points out how 1 of list items based on myinteger
search
ps: new mongo thro java, excuse ignorance
you can insert new list item using $push operator.
you can run following command on shell add new list item.
db.myobject.update({"myid" : "a string id created"},{$push:{mylist: {mystring:"new string", myinteger:9003}}})
you can add list item using java driver follows.
dbcollection coll = db.getcollection("myobject"); dbobject query = new basicdbobject("myid", "a string id created"); dbobject listitem = new basicdbobject(); listitem.put("mystring", "my new string"); listitem.put("myinteger", 9003); dbobject updateobj = new basicdbobject("mylist", listitem); coll.update(query, new basicdbobject("$push", updateobj));
you can single element follows on shell.
db.myobject.find({"mylist.myinteger" : 9003}, {"mylist.$" : 1})
from java driver can run same code follows :
dbcursor cur = coll.find(new basicdbobject("mylist.myinteger", 9003), new basicdbobject("mylist.$", 1));
you can remove object follows :
db.nested.update({"myid" : "a string id created"},{$pull:{mylist: {mystring:"new string", myinteger:9003}}})
in java can follows :
dbcollection coll = db.getcollection("myobject"); dbobject query = new basicdbobject("myid", "a string id created"); dbobject listitem = new basicdbobject(); listitem.put("mystring", "my new string"); listitem.put("myinteger", 9003); dbobject updateobj = new basicdbobject("mylist", listitem); coll.update(query, new basicdbobject("$pull", updateobj));
ps : not possible update items in array. there open issue on jira. can check jira-1243
Comments
Post a Comment