简体   繁体   中英

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

I have a document in collection names user which is as follows:

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

I want to insert an inner document job_desc having some entries like job , place , salary after modifying the user document becomes like this

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

I tried using append but it is for new document entry and then using $set but it is used for replacing the specified value. How do I meet my requirement?

Insert a new nested object using 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",
    }
}

In mongo console use this code for adding just one value to your existing nested doc(or event non existing):

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

the result would be:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM