![](/img/trans.png)
[英]how can we append/update sub-document of collction in MongoDB using MongoDB Java driver?
[英]MongoDB Java Driver Update Sub-Document
我正在尝试通过MongoDB Java驱动程序更新子文档。
我在Mongo中具有以下结构:
{
"_id" : "9999996978c9df5b02999999",
"title" : "The Effects of Glaze on Pottery",
"numberOfDownloads" : "453",
"summary" : "This is a summary of the document",
"documents" : {
"file" : "99991F64C16E9A0954E89999",
"mimetype" : "document/pdf",
"pages" : "415",
"downloads" : "453"
}
}
并使用Java驱动程序,可以通过以下方式很好地更新根文档“ numberOfDownloads”字段:
Document updDocQuery = new Document("_id", "9999996978c9df5b02999999");
Document updDocValues = new Document("numberOfDownloads","555");
Document updDocSet = new Document("$set",updDocValues);
System.out.println(updDocSet.toJson());
collection.updateOne(updDocQuery, updDocSet);
哪个工作正常。
现在,我还尝试更新SubDocument的“文档”,以将“下载”值设置为相同的值-我正在尝试如下操作:
Document updDocQuery = new Document("_id", "9999996978c9df5b02999999");
Document updDocValues = new Document("numberOfDownloads","555");
Document updSubDocValues = new Document("downloads","555");
updDocValues.append("documents", updSubDocValues);
Document updDocSet = new Document("$set",updDocValues);
System.out.println(updDocSet.toJson());
collection.updateOne(updDocQuery, updDocSet);
它将适当地将“ documents”属性更新为我的新值-但我想更新特定字段并保留其他字段不变。
我最终在Mongo中生成了以下文档:
{
"_id" : "9999996978c9df5b02999999",
"title" : "The Effects of Glaze on Pottery",
"numberOfDownloads" : "555",
"summary" : "This is a summary of the document",
"documents" : {
"downloads" : "555"
}
}
我需要它是:
{
"_id" : "9999996978c9df5b02999999",
"title" : "The Effects of Glaze on Pottery",
"numberOfDownloads" : "555",
"summary" : "This is a summary of the document",
"documents" : {
"file" : "99991F64C16E9A0954E89999",
"mimetype" : "document/pdf",
"pages" : "415",
"downloads" : "555"
}
}
我希望不必拉记录,将其转换为对象,更新值并提交以进行更新-但这似乎效率很低。
我可以从Mongo Console执行此查询,并且效果很好:
db.Paper.update(
{"_id" : "5617776978c9df5b02f68228"},
{$set:
{ "numberOfDownloads" : "453",
"documents" :
{ "downloads" : "453"}
}
});
我只是错过了一些简单的东西吗-或-我是否过于复杂化了?
如果这是在mongodb中设置的更新:
{$set:
{ "numberOfDownloads" : "453",
"documents" :
{ "downloads" : "453"}
}
}
您可以通过以下方式使用Document类:
Document upDocValue = new Document("numberOfDownloads": "453")
.append("documents.downloads":"453");
这将为您提供:
{
"numberOfDownloads": "453",
"documents" :
{ "downloads" : "453"}
}
然后,您可以使用以下命令创建外部文档:
Document upDocSet = new Document("$set",updDocValue);
这应该给您:
{$set:
{ "numberOfDownloads" : "453",
"documents" :
{ "downloads" : "453"}
}
}
然后,您在此处运行查询:
collection.updateOne(upDocQuery,upDocSet);
因此,您最终拥有:
Document updDocQuery = new Document("_id", "9999996978c9df5b02999999");
Document upDocValue = new Document("numberOfDownloads": "453")
.append("documents.downloads":"453");
Document upDocSet = new Document("$set",updDocValue);
collection.updateOne(upDocQuery,upDocSet);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.