Sush
Sush

Reputation: 1457

mongo db update a field with another jsondata

i have a mongo db table like

{
    "_id": ObjectId("531963b60748a6078fe4f345"),
    "acces": "172.1.6.2.18",
    "adapter": "Win 9",
    "flavour": "LokiSnap",
    "jobid": "8",
    "os": "VM-WIN7-32",
    "results": "",
    "tests": "Test01"
}

here result field is "" . How can i update this table value result with {"test" : "conenct","os":"osf"} based on jobid

after updating table is

{
"_id": ObjectId("531963b60748a6078fe4f345"),
"acces": "172.1.6.2.18",
"adapter": "Win 9",
"flavour": "LokiSnap",
"jobid": "8",
"os": "VM-WIN7-32",
"results": {
    "test": "conenct",
    "os": "osf"
}`,
"tests": "Test01"

}

Upvotes: 1

Views: 90

Answers (2)

Hardik Barot
Hardik Barot

Reputation: 775

Yes, Use $set so that you don't destroy the whole document and just set field/fields

This is the query for update one document

db.coll.update(
    {"jobid": "8"}, // the filter based on jobid
    {
        $set: { "results": { "test": "conenct", "os": "osf" } }
    } 
)

This is the query for update all documents

db.coll.update(
    {"jobid": "8"}, // the filter based on jobid
    {
        $set: { "results": { "test": "conenct", "os": "osf" } }
    } ,
   { multi: true }
)

Note:- Here, "coll" is your collection name.

Upvotes: 5

Neil Lunn
Neil Lunn

Reputation: 151072

Use $set so you don't destroy the whole document and just set one field

coll.update(
    { "_id": ObjectId("531963b60748a6078fe4f345") }, // the filter
    {
        $set: { "results": { "test": "conenct", "os": "osf" } },
    } 
)

Upvotes: 2

Related Questions