1

I have the following document:

{
    "results" : [ 
        {
            "name" : "foo",
            "score" : 10
        }, 
        {
            "name" : "bar"
        }
    ]
}

I want to multiply the score field by 10, only where it exists.

Using just dot notation:

{
    $mul: {
        'results.score': NumberInt(10)
    }
}

Returns an error:

Cannot create field 'score' in element {results: [ { name: "foo", score: 10 }, { name: "bar" } ]}

I've tried using the new array filters:

{
    $mul: {
        'results.$[result].score': NumberInt(10)
    }
}, {
    arrayFilters: [{
        'result.grade': {
            $exists: true
        }
    }]
}

This gives me an error too:

No array filter found for identifier 'result' in path 'results.$[result].score'

I know that I could set a score field in all the documents and set it to zero, that wouldn't be a solution though as the lack of a score means that there isn't a score yet, rather that there is a score and it's 0.

  1. Can this be done?
  2. Could this be done prior to version 3.6?
BanksySan
  • 27,362
  • 33
  • 117
  • 216
  • 1
    2 issues I found, your `arrayFilters` option is referencing the wrong field and it looks like you are running your query in Robomongo which won't work. Try mongo shell instead and the correct query should be `db.collection.update( { "results.score": { "$exists": true } }, { "$mul": { "results.$[result].score": 10 } }, { "arrayFilters": [{ "result.score": { "$exists": true } }], "multi": true } )` – chridam Jan 18 '18 at 12:13
  • 1
    @chridam That's it. Thank you. I dread to think ho wlong it would have taken me to figure out that it didn't work in RoboMongo. – BanksySan Jan 18 '18 at 13:11

0 Answers0