java - How to dynamically change the document structure, merge into an array from a scalar value? -
i have collection of documents:
{"name":1,"b":3,"c":3} {"name":1,"b":3,"c":5} {"name":1,"b":3,"c":6} {"name":2,"b":6,"c":6} {"name":2,"b":6,"c":7} {"name":2,"b":6,"c":3} {"name":3,"b":2,"c":3} {"name":4,"b":2,"c":3} i merge collection following result:
{"name":1,"b":3,"c":[3,5,6]} {"name":2,"b":6,"c":[6,7,3]} {"name":3,"b":2,"c":3} {"name":4,"b":2,"c":3} which means eliminating duplicate documents , save c fields array. c array.
notes: first(e.g. "name") , second(e.g"b") fields unique per document.
while (cursor.hasnext()) { dbobject currentobject = cursor.next(); string currentname = (string)currentobject.get("name"); if (currentname.equals(previousname) && !previousname.equals("")) { // should write here collection.remove(previousobject); } previousobject = currentobject; previousname = (string)previousobject.get("name"); }
you can hold map of names , dbobjects , push value progress, this:
map<string,dbobject> names = new hashmap<string, dbobject>(); while (cursor.hasnext()) { dbobject currentobject = cursor.next(); string currentname = (string) currentobject.get("name"); dbobject o = names.get(currentname); if (o!=null) { //means have it. integer c = (integer) currentobject.get("c"); collection.remove(currentobject); collection.update(o,new basicdbobject("$push",new basicdbobject("c",c))); }else { names.put(currentname,currentobject); } }
Comments
Post a Comment