Your syntax is a bit messed up. You cannot use the dot
notation in Java
. You need to create
and embed
objects.
To generate the equivalent of:
{ "field1" : { "field2" : [ { "a" : "aa"} , { "b" : "bb"}]}}
you need to do the following operations,
BasicDBList list = new BasicDBList();
list.add(new BasicDBObject("a","aa"));
list.add(new BasicDBObject("b","bb"));
DBObject fieldTwo = new BasicDBObject("field2",list);
DBObject fieldOne = new BasicDBObject("field1",fieldTwo);
Similarly, to push something inside an existing list
you need to,
while (cursor.hasNext()) {
BasicDBObject obj = (BasicDBObject) cursor.next();
BasicDBObject fieldOne = (BasicDBObject)(obj.get("field1"));
// get the list
BasicDBList field2List = (BasicDBList)(fieldOne.get("field2"));
// add something to it
field2List.add(new BasicDBObject("a","aa"));
list.add(new BasicDBObject("b","bb"));
list.add(new BasicDBObject("c","cc"));
//save it
this.dataColl.save(obj);
}
would give you,
{ "field1" : { "field2" : [ { "a" : "aa"} , { "b" : "bb"} , { "c" : "cc"}]}}
BasicDBObject
takes a key name
and a value
as its arguments.A key
name cannot contain the .
operator in it. That is why you get the error:
Invalid BSON field name field1.field2