$mul nested document field where might not exist

2019-08-06 04:15发布

问题:

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?