[英]How to Update fields value in embedded documents of an Array in MongoDB using Java Driver
I have the following structure in my document: 我的文档中具有以下结构:
{
"_id": ObjectId("5891a85bccaad513a844308f"),
"sites": [
{
"site": "site1",
"url": "site1.com",
"status": 1,
},
{
"site": "site2",
"url": "site2.com",
"status": 1,
},
{
"site": "site3",
"url": "site3.com",
"status": 1,
}
]
}
then I load all sites to UI. 然后将所有网站加载到UI。 then I'll do some changes like following image and hit Update.
然后我将做一些更改,例如下图并单击“更新”。 I have deleted "site3".
我已删除“ site3”。
then My structure should update like as follow.
然后我的结构应如下更新。 site3 status should update to 0
site3状态应更新为0
{
"_id": ObjectId("5891a85bccaad513a844308f"),
"sites": [
{
"site": "site1",
"url": "site1.com",
"status": 1,
},
{
"site": "site2",
"url": "site2.com",
"status": 1,
},
{
"site": "site3",
"url": "site3.com",
"status": 0,
}
]
}
How can I achieve this ? 我该如何实现?
You can make use of positional $
update. 您可以使用位置
$
更新。
The query filter finds the matching site
in the array and update part will set the status
to 0 to matching element. 查询过滤器在数组中找到匹配的
site
,更新部分会将匹配元素的status
设置为0。
collection.updateOne(new Document("_id", new ObjectId("5891a85bccaad513a844308f")).append("sites.site", "site3"), Updates.set("sites.$.status", 0));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.