簡體   English   中英

如何使用Java MongoDB驅動程序在嵌套的BasicDBObject中設置值

[英]How to set value in nested BasicDBObject with Java MongoDB driver

我在插入mongodb之前嘗試更新一個mongo文檔。

我必須把這三個關鍵

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

您是否嘗試過$push運算符?

例:

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

在您的示例中:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM