Java MongoClient 添加新的嵌入文档

问题描述

我在 mongodb 中有以下数据类型

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

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

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

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

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

解决方法

更新代码:

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/

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...