$project: Is it possible to access a property of an expression result in just one single stage?

我们两清 提交于 2020-07-30 07:14:08

问题


Is there any way to carry out the following operation in just one $project stage?

db.getCollection('users').aggregate([
    {
        $project : {
            firstEmail : { $arrayElemAt : ["$emails", 0] }
        }
    },
    {
        $project : {
            domain : "$firstEmail.domain"
        }
    }
])

回答1:


You need $let operator:

db.getCollection('users').aggregate([
    {
        $project : {
            domain : {
                $let: {
                    vars: { firstEmail: { $arrayElemAt : ["$emails", 0] } },
                    in: "$$firstEmail.domain"
                }
            }
        }
    }
])

Mongo Playground




回答2:


When working with array of objects, you can automatically get array of objects's properties with the dot notation. So the following will perfectly work :

db.getCollection('users').aggregate([
    {
        $project : {
            domain: { $arrayElemAt : ["$emails.domain", 0] }
        }
    }, 
])

Mongo playground



来源:https://stackoverflow.com/questions/60287936/project-is-it-possible-to-access-a-property-of-an-expression-result-in-just-on

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