arun kumar
arun kumar

Reputation: 147

MongoDB- Add new field from existing array

I am the beginner of the MongoDB

Here I mentioned my database schema

{
"_id" : ObjectId("5e72067973c1241068a13647"),
"client_id" : "1001",
"dependent" : [ 
    {
        "dependent_name" : "asdsa",
        "dependent_id" : "DE100"
    }, 
    {
        "dependent_name" : "fdggd",
        "dependent_id" : "DE101"
    }
  ]
}

I want to add new field based on client_id and dependent_id

Here I mentioned My query but cannot able to get my expected result

 db.collection.update({"client_id" : "1001","dependent.dependent_id":"DE101"}, {"$push": {"reason":"expired"}})

I am Expected Result is

 {
"_id" : ObjectId("5e72067973c1241068a13647"),
"client_id" : "1001",
"dependent" : [ 
    {
        "dependent_name" : "asdsa",
        "dependent_id" : "DE100"
    }, 
    {
        "dependent_name" : "fdggd",
        "dependent_id" : "DE101",
        "reason":"expired"
    }
  ]
}

so anyone help me to solve this

Upvotes: 1

Views: 264

Answers (2)

SANJEEV RAVI
SANJEEV RAVI

Reputation: 179

db.collection.update({"client_id" : "1001","dependent.dependent_id":"DE101"}, 
{$set:
{"dependent.$.reason":"expired"}})

Try this it works for me using $

Upvotes: 1

Amit Joshi
Amit Joshi

Reputation: 474

As i am also new to mongodb, as i tried, i can give you suggestion to update whole document or replace it.
both way i tried, and query is as below.
Update

db.updateColl.update({ 'dependent.dependent_id': 'DE101' },
    {
        $set: {
            "dependent": [
                {
                    "dependent_name": "asdsa",
                    "dependent_id": "DE100"
                },
                {
                    "dependent_name": "fdggd",
                    "dependent_id": "DE101",
                    "reason": "expired"
                }
            ]
        }
    });  

Replace

db.updateColl.replaceOne({ 'dependent.dependent_id': 'DE101' }, {
    "dependent": [
        {
            "dependent_name": "asdsa",
            "dependent_id": "DE100"
        },
        {
            "dependent_name": "fdggd",
            "dependent_id": "DE101",
            "reason": "expired"
        }
    ]
})  

may be it can help you. if any suggestion regarding it wellcome.

Upvotes: 0

Related Questions