问题
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