1

my document object looks like this

{ 
   "_id" : ObjectId("5b62cfac2046e98de373399c"),
   "hindi" : {
    "confirmed" : false, 
    "assigned_to" : "[email protected]", 
    "candidates" : [

            {
            "candidate_id" : "9262c520-9640-11e8-bfbf-292ac77d55f9", 
            "value" : "स्क्रॉल कैसे करें ?", 
            "createdAt" : NumberInt(1533207154), 
            "createdBy" : "[email protected]", 
            "warningList" : [], 
            "comments" : [
                "Correction कैसे स्क्रॉल करें", 
                "added ?"
            ]
           }, 
           {
            "candidate_id" : "297bb060-9642-11e8-ac2d-93ac27f5ee90", 
            "value" : "स्क्रॉल कैसे करें ?", 
            "createdAt" : NumberInt(1533207154), 
            "createdBy" : "[email protected]", 
            "warningList" : [], 
            "comments" : [
                "Correction कैसे स्क्रॉल करें", 
                "added ?"
            ]
          }
    ]
}

My objective is to find an particular item inside candidates array by the candidate_id and update the comment field.

Here is the query I'm trying with MongoDB positional operator($) but getting an error Unsupported projection option: $set: { hindi.candidates.$.comments: [] }

db.getCollection("strings").update({_id: ObjectId("5b62cfac2046e98de373399c"),"hindi.candidates.candidate_id": "297bb060-9642-11e8-ac2d-93ac27f5ee90"}, {$set :{"hindi.candidates.$.comments" : []}})
5
  • Do you want to push something in commentsarray or want to $set it as []? Commented Aug 2, 2018 at 18:41
  • Correct syntax is db.getCollection("strings").update( { "_id": ObjectId("5b62cfac2046e98de373399c"), "hindi.candidates": { "$elemMatch": { "candidate_id": "297bb060-9642-11e8-ac2d-93ac27f5ee90" } } }, { "$set": { "hindi.candidates.$.comments" : [] }} ) Commented Aug 2, 2018 at 18:47
  • @AnthonyWinzlet it depends on the requrement, sometimes just needs to be set as empty, sometimes it can contain new values Commented Aug 2, 2018 at 18:56
  • you have used incorrect syntax for update query... Try the above one Commented Aug 2, 2018 at 18:59
  • @AnthonyWinzlet working fine now. could you please elaborate what was the mistakes? Commented Aug 2, 2018 at 19:04

1 Answer 1

1

You need to use $elemMatch here to match inside an array

db.getCollection("strings").update(
  {
    "_id": ObjectId("5b62cfac2046e98de373399c"),
    "hindi.candidates": { "$elemMatch": { "candidate_id": "297bb060-9642-11e8-ac2d-93ac27f5ee90" } }
  }, 
  { "$set": { "hindi.candidates.$.comments" : [] }}
)
Sign up to request clarification or add additional context in comments.

Comments

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.