在mongodb的陣列更新值I具有幾個documens的MongoDB中如下:在從Java
{
"_id" : ObjectId("54901212f315dce7077204af"),
"Date" : ISODate("2014-10-20T04:00:00.000Z"),
"Type" : "Twitter",
"Entities" : [
{
"ID" : 4,
"Name" : "test1",
"Sentiment" : {
"Value" : 20,
"Neutral" : 1
}
},
{
"ID" : 5,
"Name" : "test5",
"Sentiment" : {
"Value" : 10,
"Neutral" : 1
}
}
]
}
現在我想更新由具有Entities.ID = 4的文件加入(Sentiment.Value + 4)/ 2例如,在更新後,我們有12
我寫了下面的代碼,但我被困在if語句中,你可以看到上面的例子:
DBCollection collectionG;
collectionG = db.getCollection("GraphDataCollection");
int entityID = 4;
String entityName = "test";
BasicDBObject queryingObject = new BasicDBObject();
queryingObject.put("Entities.ID", entityID);
DBCursor cursor = collectionG.find(queryingObject);
if (cursor.hasNext())
{
BasicDBObject existingDocument = new BasicDBObject("Entities.ID", entityID);
//not sure how to update the sentiment.value for entityid=4
}
首先,我認爲我應該首先展開Entities數組以獲得情感價值,但如果我這樣做,那麼我怎樣才能再次使用它們並使用與現在相同的格式更新文檔,但是使用新的情感值?
我也發現了這個鏈接,以及: MongoDB - Update objects in a document's array (nested updating)
,但我不明白它,因爲它不是用Java寫的查詢, 任何人都可以解釋我是如何在Java中做到這一點?
http://stackoverflow.com/a/12103403/1254903 這會有幫助嗎? –
不,因爲它不是一個簡單的更新我需要獲得該entityid的當前情緒值,並將其添加例如4並將其除以2 –
我認爲您問題中描述的文檔與實際結構不同建議去做。沒有字段,例如'sentiment.value',執行所提到的操作我們得到的值爲12.你能檢查文檔結構是否正確? – BatScream