1

I have this structure in collection. i want to update "remark" to "Better" if "language" is "english".

{"Information":[{"id":"5245","details":[{"language":"english","remark":"good","status":"published"},{"language":"hindi","remark":"good","status":"published"},{"language":"arabic","remark":"good","status":"published"}]}],"name":"saroj","company":"visa"}

i am able to get the particular section of data from db based on language

db.getCollection("containts").aggregate([
// Filter possible documents
{ "$match": {"$and": [{ "Information.id": "1" },{ "name": "saroj" }]}},

// Unwind the array to denormalize
{ "$unwind": "Information" },
{ "$unwind": "Information.details" },

// Match specific array elements
{ "$match": { "Information.detail.language": "english" } },

// Group back to array form
{ "$group": {
    "_id": "$_id",
    "details": { "$push": "Information.details" }
}}])

Output:

{  "details": [{
  "language": "english",
  "remark": "good",
  "status": "published"
}]}

But i am unable to update "remark" based on "language"

1 Answer 1

1

You can use arrayFilters to update the element inside the array if you are using mongodb 3.6 and above. I have used the same array that you have mentioned in the question above and tested the below query which returns the updated document.

db.collectionName.findOneAndUpdate(
    { "Information.id": "5245", "name": "saroj"},
    { $set : {"Information.$[outer].details.$[elem].remark" : "better"}},
    {   
        returnNewDocument : true,
        arrayFilters: [{"elem.language": "english"},{ "outer.id": "5245"}]
    }
 )

you can get a detailed explanation about arrayFilters here.

Aditionally to get the updated document as a result, in mongoose you can use {new : true} instead of returnNewDocument: true (this is used in mongodb shell).

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

1 Comment

can i use upsert:true here to insert if the searched data is not available ? i tried its not working can you suggest soemthing

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.