db.getCollection("user").aggregate([
{ $match : { fname : "test1" } },
{ $addFields: { email_address : "[email protected]" } },
{ $match : { fname : "test2" } },
{ $addFields: { email_address : "[email protected]" } }
])
I just want to add email address depends on fname value. This code works only when there's no test2 so works once but don't repeat. is there any ways I can repeat match and addfields?
CodePudding user response:
You can use $switch
for your case.
db.collection.aggregate([
{
"$addFields": {
"email_address": {
"$switch": {
"branches": [
{
"case": {
$eq: [
"$fname",
"test1"
]
},
"then": "[email protected]"
},
{
"case": {
$eq: [
"$fname",
"test2"
]
},
"then": "[email protected]"
}
]
}
}
}
}
])
Here is the Mongo playground for your reference.
CodePudding user response:
In the generalized case (in case it is applicable):
db.getCollection("user").aggregate([
{ $addFields: { email_address : {$concat: ["$fname", "@gmail.com"]} }}
])