Reputation: 705
I need to perform an aggregate on a mongodb collection. The issue I'm having is that I need to do an OR operation in a group function.
My documents have different keys for values where ideally they should be the same. I'm stuck with these values so I cannot just normalise the data.
For example the collection has three different field values for an email field :
{
_id : 1,
name : "docType1",
e_mail : "[email protected]"
}
{
_id : 2,
name : "docType2",
email : "[email protected]"
}
{
_id : 3,
name : "docType3",
mail : "[email protected]"
}
Is it possible to perform a group function that groups the documents by the email values once the key is either e_mail, email or mail?
Perhaps its possible in combination with a project but I've been unsuccessful in my attempts so far is I think I would also need an OR here?
Upvotes: 1
Views: 226
Reputation: 151112
Yes it is possible with the aggregation framework. You basically need to test with the $ifNull
operator and use the second condition in a nested form:
db.collection.aggregate([
{ "$group": {
"_id": { "$ifNull": [
"$e_mail",
{ "$ifNull": [
"$email",
{ "$ifNull": [
"$mail",
false
]}
]}
]},
"count": { "$sum": 1 }
}},
{ "$match": { "_id": { "$ne": false } } }
])
So the $ifNull
takes two arguments, the first being the field to test which is returned where it exists or is not null, and the second is the alternate value to return where the condition is not true
.
Upvotes: 3