如何使用Java MongoDB驱动程序在嵌套的BasicDBObject中设置值

时间:2014-09-18 12:58:26

标签: java mongodb mongodb-java nosql

我有一个mongo文档,我想在插入mongodb之前更新。

我必须把这些3键

document._parentId = ObjectId()
document.aDictionnary.actionId = Integer
document.aDictionnary.bDictionnary.id = Integer

我尝试了一些组合,但无法使其发挥作用。

这是我目前的代码

myClass.getDocument().append( "$set", new BasicDBObject().append("_parentId", myClass.getDocument.getId() ) );
myClass.getDocument().append( "$set", new BasicDBObject().append("aDictionnary", new BasicDBObject().append("actionId", actionToAttachId ) ) );

if( null == myClass.getSiteId() )
{
    myClass.getDocument().append( "$set", new BasicDBObject().append("aDictionnary", new BasicDBObject().append("bDictionnary", new BasicDBObject().append( "id", actionToAttach.getSiteId() ))));
}

我不想直接在数据库中更新我的文档,原因是我保留了所有历史记录,因此每个条目都是一个新插入。

应用程序不会崩溃,但由于错误的“追加”语法

而导致插入失败

另外我认为由于嵌套的basicdbobject.append语法编写这种代码是不愉快的,还有另一种方法吗?

这是堆栈跟踪

163530 [http-8080-8] ERROR com.myapp.persistance.mystuff.MyClassMongo  - java.lang.IllegalArgumentException: fields stored in the db can't start with '$' (Bad Key: '$set')

2 个答案:

答案 0 :(得分:0)

您是否尝试过$push运营商?

示例:

db.students.update({ _id: 1 },{ $push: { scores: 89 }})

答案 1 :(得分:0)

在你的例子中:

document._parentId = ObjectId()
document.aDictionnary.actionId = Integer
document.aDictionnary.bDictionnary.id = Integer

基本上相当于:

{_parentId: ObjectId(), aDictionary: {actionId: actionId,
                                      bDictionnary: {id: id}}

所以有3个文档 - 一直到顶层嵌套bDictionnary。其中每个都是DBObject,因此您需要构建DBObject并将其保存为适当的 - 这是一些未经测试的伪代码:

DBObject myDocument = new BasicDBObject();
myDocument.put("_parentId", ObjectId())
DBObject aDictionary = new BasicDBObject("actionId", actionId)
                           .append("bDictionary", new BasicDBObject("id", id))
myDocument.put("aDictionary", aDictionary)

db.save(myDocument)