gpt4 book ai didi

java - 如何更新结构复杂的Mongodb文档

转载 作者:行者123 更新时间:2023-12-01 10:14:49 36 4
gpt4 key购买 nike

我有一个具有以下结构的 mongoDB 文档

{
"id": 9595511812,
"Feeds": [
{
"department": "mseb",
"consumer_number": 1234567890,
"due_date": "2016-11-11",
"due_amount": 400,
"balance_amount": 0,
"unitsConsumed": 40,
"freezeDate": "2016-11-11",
"lastPaidDate": "2016-11-11",
"billNumber": "9877",
"id": "1",
"paid": false
},
{
"department": "mseb",
"consumer_number": 1234567890,
"due_date": "2016-11-21",
"due_amount": 400,
"balance_amount": 0,
"unitsConsumed": 40,
"freezeDate": "2016-11-21",
"lastPaidDate": "2016-11-21",
"billNumber": "9877",
**"id": "2",**
"paid": false
}
]
}

我想为 id=2 的 Feed 更新paid == true(** 上面标记的字段)。如何使用 mongo java 客户端做到这一点?

我已经尝试过

 DB db = DBConnection.getDatabaseConnection();
DBCollection table = db.getCollection("customer");
BasicDBObject newDocument = new BasicDBObject();
newDocument.append("$set", new BasicDBObject().append("Feeds.paid", "true"));

BasicDBObject searchQuery = new BasicDBObject().append("id", "9595511812");

table.update(searchQuery, newDocument);

最佳答案

Feeds 是一个数组,您要更新第二个元素,因此 set 将以:

.append("Feeds.1.paid", "true"));

而不是:

.append("Feeds.paid", "true"));

关于java - 如何更新结构复杂的Mongodb文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35962819/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com