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

时间:2015-01-13 12:33:21

标签: java mongodb

我在集合名称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,但它用于替换指定的值。我如何满足我的要求?

1 个答案:

答案 0 :(得分:2)

使用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控制台中使用此代码只为现有的嵌套doc(或不存在的事件)添加一个值:

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"
    }
}