1

I've got a problem updating an array element in MongoDB. This is the structure of a document:

{
        "_id" : ObjectId("57e2645e11c979157400046e"),
        "site" : "BLABLA",
        "timestamp_hour" : 1473343200,
        "values" : [
                {
                        "1473343200" : 66
                },
                {
                        "1473344100" : 230
                },
                {
                        "1473345000" : 479
                },
                {
                        "1473345900" : 139
                }
        ]
}

Now I want to update the element with key "1473345900". How can I do this? I've tried:

db.COLLECTIONNAME.update({"values.1473345900": {$exists:true}}, {$set: {"values.$": 0}})

But after that the document looks like:

{
        "_id" : ObjectId("57e2645e11c979157400046e"),
        "site" : "BLABLA",
        "timestamp_hour" : 1473343200,
        "values" : [
                {
                        "1473343200" : 66
                },
                {
                        "1473344100" : 230
                },
                {
                        "1473345000" : 479
                },
                0
        ]
}

What I'm doing wrong? I only want to update the value of 1473345900 to any value... I don't want to update the complete element...

Thanks a lot!!!

1 Answer 1

4

You need to add an additional query in your update that matches the array element you want to update. A typical query would involve checking for the element's value not equal to the one being updated.

The following example update shows this where the $ positional operator identifies the correct index position of the hash key array element { "1473345900": 139 }. If you try to run the update operation without the $ positional operator:

db.COLLECTIONNAME.update(
    { "values.1473345900": { "$exists": true } }, 
    { "$set": { "values.1473345900": 0 } }
)

mongo will treat the timestamp 1473345900 as the index position and thus you will get the error

can't backfill array to larger than 1500000 elements

Thus the correct way should be:

var val = 32;   
db.COLLECTIONNAME.update(
    { "values.1473345900": { "$ne": val, "$exists": true } },
    { "$set": { "values.$.1473345900": val } }
)
Sign up to request clarification or add additional context in comments.

2 Comments

The problem is: I don't know if 1473345900 already exists. So 1) I have to find out if 1473345900 exists and 2) I have to update the value of 1473345900. Sorry, I missed to explain that...
db.sites.update({"values.1473345900": {$exists:true}}, {$set: {"values.$.1473345900": 0}}) will work do it. Thx, Chridam!!!

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.