Java,MongoDB:如何插入子文档的空数组

时间:2015-12-23 21:39:57

标签: java mongodb

我正在做loop-and-update,类似于this

我有一个现有的文档,其字段如下:

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

使用空数组。

使用Java,如何将文档放在空数组中?

这样做......

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

我收到错误消息:

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

JavaScript中,您可以轻松实现,例如:

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

有什么想法吗?

提前致谢。

1 个答案:

答案 0 :(得分:3)

你的语法有点搞砸了。您无法在dot中使用Java表示法。您需要createembed个对象。

生成相当于:

{ "field1" : { "field2" : [ { "a" : "aa"} , { "b" : "bb"}]}}

您需要执行以下操作,

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);

同样,要在现有的list内推送一些内容,

  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);
  }

会给你,

{ "field1" : { "field2" : [ { "a" : "aa"} , { "b" : "bb"} , { "c" : "cc"}]}}

BasicDBObject会将密钥namevalue作为参数。key名称中不能包含.运算符。这就是你得到错误的原因:

Invalid BSON field name field1.field2