2

我在 mongodb 中有以下数据类型

{
    "_id" : ObjectId("60007b3abc54b5305e9f5601"),
    "description" : "Mens",
    "name" : "Men"
}

由于上述数据已经是现有数据,现在使用 MongoClient 我想根据_id插入新的嵌入文档,如下所示

{
    "_id" : ObjectId("60007b3abc54b5305e9f5601"),
    "description" : "Mens",
    "name" : "Men",
    "subCategory" : [{
        "name" : "This is name update",
        "description" : "This is update"
    }]
}

一次,数组已被插入,我再次需要向数组中添加另一个项目,如下所示

{
    "_id" : ObjectId("60007b3abc54b5305e9f5601"),
    "description" : "Mens",
    "name" : "Men",
    "subCategory" : [{
        "name" : "This is name update",
        "description" : "This is update"
    },
{
        "name" : "This is name update",
        "description" : "This is update"
    }]
}
4

1 回答 1

1

要更新的代码:

import static com.mongodb.client.model.Filters.eq;

MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("some_db_name");
MongoCollection<Document> collection = database.getCollection("some_database");
Document document = collection.find(eq("_id", new ObjectId("60007b3abc54b5305e9f5601")))
                              .first();

Object object = document.get("subCategory");

List<Document> documents = new ArrayList<>();

if(object != null) {
  documents = (List<Document>) object;
}

documents.add(new Document("name", "This is name update")
              .append("description", "This is update")); 

document.append("subCategory", documents);

collection.updateOne(eq("_id", new ObjectId("60007b3abc54b5305e9f5601")), 
         new Document("$set", new Document("subCategory", documents)));

 

阅读文档:https ://mongodb.github.io/mongo-java-driver/3.4/driver/getting-started/quick-start/

于 2021-01-23T14:39:55.857 回答