简体   繁体   English

如何使用Java驱动程序在MongoDB中更新数组的嵌入式文档中的字段值

[英]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.

相关问题 使用MongoDB Java Driver更新嵌入式文档中的字段? - Updating fields in embedded documents with MongoDB Java Driver? 使用Java更新数组中的嵌入式文档,而无需在MongoDb中重复 - Update Embedded Documents in array without Repeating in MongoDb using Java 如何使用mongodb Java驱动程序更新较旧的文档? - How can I update older documents using mongodb Java driver? 使用 mongodb java 驱动程序保证 mongodb 文档中的字段顺序 - guarantee fields order in a mongodb documents using mongodb java driver 从文档嵌入式数组Mongodb Java获取字段的键 - Get keys of fields from Embedded Array of Documents Mongodb Java 如何使用 MongoDB Java 驱动程序更新数组中的 object? - How to update an object in a array using MongoDB Java Driver? Java MongoDB 驱动程序:如何更新集合中的所有文档? - Java MongoDB driver: How to update all Documents in Collection? 使用Java驱动程序从MongoDB中的数组中检索一组文档 - Retrive a set of documents from array in MongoDB using Java driver 如何使用java驱动程序更新mongo db中的文档字段? - How do I update fields of documents in mongo db using the java driver? 使用 Java 驱动程序过滤 mongodb 文档中的嵌入数组 object - Filter embedded Array object in mongodb document using Java driver
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM