如何在 mongodb in java 中的现有文档中插入内部文档?

How do insert an inner document in an existing document in mongodb in java?

我在集合名称 user 中有一个文档,如下所示:

{
    "_id" : "abc@gmail.com",
    "Password" : "xyz",
    "first_name" : "ABC",
    "last_name" : "PQR",
}

我想插入一个内部文档 job_desc,其中包含一些条目,例如 jobplacesalary 修改后user文档变成这样

{
    "_id" : "abc@gmail.com",
    "Password" : "xyz",
    "first_name" : "ABC",
    "last_name" : "PQR",
    "doc" : { "job_desc" : "Design Engineer", "place" : "Bengaluru", "salary" : 40K USD }
}

我尝试使用 append 但它用于新文档输入,然后使用 $set 但它用于替换指定值。如何满足我的要求?

使用 Java

插入新的嵌套对象
BasicDBObject doc = new BasicDBObject("doc",new BasicDBObject("job","Design Engineer").append("place","Bengaluru").append("salary", "40K USD"));
    BasicDBObject query = new BasicDBObject();
    query.put("_id","abc@gmail.com");
    BasicDBObject set = new BasicDBObject("$set", doc);
    collection.update(query, set);

// result doc
{
    "_id" : "abc@gmail.com",
    "Password" : "xyz",
    "first_name" : "ABC",
    "last_name" : "PQR",
    "doc" : {
        "job" : "Design Engineer",
        "place" : "Bengaluru",
        "salary" : "40K USD",
    }
}

在 mongo 控制台中使用此代码仅向现有嵌套文档(或不存在的事件)添加一个值:

db.collection.update({"_id":"abc@gmail.com"}, {$set : {'doc.newField' : 'newValue'}})

结果将是:

// modified doc
{
    "_id" : "abc@gmail.com",
    "Password" : "xyz",
    "first_name" : "ABC",
    "last_name" : "PQR",
    "doc" : {
        "job" : "Design Engineer",
        "place" : "Bengaluru",
        "salary" : 500,
        "newField" : "newValue"
    }
}