你如何更新文档内的文档? MongoDB Java

问题描述 投票:0回答:1

我希望更新文档中的“信息”,唯一的问题是我将其存储为doc并且似乎无法访问它。

Document doc = new Document("name", "Test")
    .append("type", "database")
    .append("count", 1)
    .append("info", new Document("a", 23).append("b", 12));

现在我希望将新信息附加到“info”,("c", 8)我尝试过doc.append("info", ... )但它只覆盖了数据。我正在考虑创建新的Document并将其设置为与doc中的文档相同,例如

Document temp = new Document();
    temp.append("info", doc.get("info"));

并更新它但它不起作用。我感谢任何建议或新方法。谢谢!

java mongodb
1个回答
0
投票

您正在寻找的是对Mongo文档更新的$ set操作。这可以更新单个字段而不会打扰其他字段。

就像是:

Document selectQuery = new Document("name", "test");
Document updateInstruction = new Document("$set", new Document("info.c", "8"));
repo.updateOne(selectQuery, updateInstruction);
© www.soinside.com 2019 - 2024. All rights reserved.