java - MongoDB query update nested list of objects -
i have users table in mongodb format looks this:
{ "_id" : objectid("id"), "user" : { "id" : "userid", "info" : "user info", "subscriptions" : [ { "subname" : "sub1", "frequency" : 1, "contentid" : "contentid" } ] } }
i add subscription object array named "subscriptions." here code looks , doesn't work. jsonparser in case work , returns correct array.
querybuilder builder = querybuilder.start("user.id").is("userid"); dbcursor cursor = mongoclient.find(builder.get()) while (cursor.hasnext()){ dbobject user = cursor.next(); basicdblist subscriptions = (basicdblist)jsonparser.parseobject(user, "user.subscriptions"); subscriptions.add(subscriptiondbobject); dbobject updatesubs = new basicdbobject(); updatesubs.put("$set", new basicdbobject("subscriptions" : subscriptions); mongoclient.update(user, updatesubs); }
this runs user never edited , writeresult returns "updatedexisting" : false. appreciate if tell me have done wrong here.
thanks
i'm not familiar java driver, won't suggest code, believe looking mongo's array update operators. think $push or $addtoset operator serve needs.
mongo's example using $push:
db.students.update( { _id: 1 }, { $push: { scores: 89 } } )
be sure understand performance implications of using growing embedded arrays in mongodb. see here: why shouldn't embed large arrays in documents?
you might find post helpful: thinking arrays in mongodb
Comments
Post a Comment