【问题标题】:Java MongoClient to add a new embedded documentJava MongoClient 添加新的嵌入文档
【发布时间】:2021-01-23 13:57:20
【问题描述】:

我在 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"
    }]
}

【问题讨论】:

    标签: java mongodb micronaut micronaut-data


    【解决方案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/

    【讨论】:

    • document.get("subCategory") 这个对象在开始时不存在。所以 List 文档 = (List) document.get("subCategory");如果 subCategory 不存在,将不起作用
    • @SanJaisy 你在吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    • 2018-08-02
    • 1970-01-01
    相关资源
    最近更新 更多