1

I have some documents like this:

doc = {
    "tag"   : "tag1",
    "field" : {
        "zone" :"zone1",
        "arr"  : [ 
            { vals: [-12.3,-1,0],     timestamp: ""},
            { vals: [-30.40,-23.2,0], timestamp: "" }
        ]
    }
}

I want to modify one of the elements of the array (for example, the first element, the one with index 0) of one of such documents.

I want to end it up looking like:

doc = {
    "tag"   : "tag1",
    "field" : {
        "zone" :"zone1",
        "arr"  : [ 
            { vals: [-1, -1, -1],       timestamp: "the_new_timestamp"},  // this one was modified
            { vals: [-30.40, -23.2, 0], timestamp: "" }
        ]
    }
}

I know something about find_and_modify:

db.mycollection.find_and_modify(
    query  = query,  // you find the document of interest with this
    fields = {  },  // you can focus on one of the fields of your document with this
    update = { "$set": data }, // you update your data with this
)

The questions that feel closer to what I want are these:

I've been going through them but I'm getting stuck when trying to work out the solution for my case. I don't know if I should really use the fields parameter. I don't know how to use $set correctly for my case.

I hope you could help me.

2
  • what is the query query = query?, how to decide need to modify which element? Commented May 9, 2021 at 18:04
  • Oh right, I'm missing that. The query will filter out one or more documents, let's say I get only one result. Then I want to select one array element by its index. Commented May 9, 2021 at 20:53

1 Answer 1

2

https://docs.mongodb.com/manual/reference/operator/update/positional/

This will help you!

db.mycollection.updateOne(
   query,
   fields,
   { $set: { "field.arr.0.timestamp": "the_new_timestamp"} }
)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, that's what I needed! Btw, for the future users. I did not use 'fields'. I didn't need it.

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.