How to perform type casting in MongoDb aggregation query in version 3.6

陌路散爱 提交于 2019-12-11 08:57:26

问题


I have a field like this

MyField : {
    "100": "1",
    "50" : "5"
}

And have another field which is int type. Call it IntField.

I want to get the value of MyField according to the value of IntField, practically what I want is MyField[IntField].

I tried to do this like this way :

$project: {
    Value : {$arrayElemAt:
                [{$filter:
                     input:{$objectToArray:"$MyField"},
                     as : "m",
                     cond:{$eq:["$$m.k","$IntField"]}} // k means key when i use objectToArray
                  },
                0]}, 
}

I expected output as 5 if IntField is 50 and 1 if IntField is 100.

However, since "$$m.k" is string and "$IntField" is int they never match.

I tried $convert but my version is lower than 4.0, so it does not work.

How can I solve this problem?. Thanks for any suggestion.

来源:https://stackoverflow.com/questions/53119588/how-to-perform-type-casting-in-mongodb-aggregation-query-in-version-3-6

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