1

I'm doing a loop-and-update, similar to this.

And I have an existing document with fields like so:

"field1" : {
    "field2" : []
}

With an empty array.

With Java, how do I put a document inside the empty array?

Doing this...

// BasicDBObject obj...
obj.put("field1.field2", 
           new BasicDBObject().append("a", "aa").append("b", "bb"));

I get an error that says:

java.lang.IllegalArgumentException: Invalid BSON field name field1.field2

In JavaScript, it's easy - you just do, like:

obj.field1.field2["a"] = "aa";

etc.

Any ideas?

Thanks in advance.

Community
  • 1
  • 1

1 Answers1

2

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
BatScream
  • 19,260
  • 4
  • 52
  • 68