【发布时间】:2015-01-08 02:22:01
【问题描述】:
我在 mongodb 中有几个文档如下:
{
"_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
}
}
]
}
现在我想通过添加 (Sentiment.Value+4)/2 来更新 Entities.ID=4 的文档,例如在更新后的示例中我们有 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 中做到这一点?
【问题讨论】:
-
不,因为这不是一个简单的更新,我需要获取该 entityid 的当前情绪值并将其添加例如 4 并除以 2
-
我认为您问题中描述的文档与您实际建议的结构不同。没有像
sentiment.value这样的字段,执行上述操作我们得到的值是12。你能检查一下文档结构是否正确吗? -
@BatScream 对不起,你是对的,我更新了文档
标签: mongodb-query mongodb-java