1

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

2 Answers 2

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

Try this it works for me using $

Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

you said update full dependent details but I want to inset one field for existing array
we can update specific field but it will add at last after dependent node, so output would not matched with yours.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.