$mul nested document field where might not exist

梦想与她 提交于 2019-12-11 06:52:05

问题


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?

来源:https://stackoverflow.com/questions/48319535/mul-nested-document-field-where-might-not-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!