I am not sure whether the title explains what I try to say.
But here assume collection's structure is like;
[
{email: "alex@sda.com"},
{email: "elizabeth@sds.com"},
{email: "hannah@xx.com"},
]
I want to get emails but before the @ character.
What have I done to achieve this?
db.collection.find({}).toArray(function(err, result){
var emails = [];
for(var i =0; i< result.length; i++){
emails.push(result[i].split("@")[0]);
}
})
But I don't find this efficient because after the query, I loop through the result and store them in new array.
Is there a better way to get only the alex, elizabeth, hannah parth with a query?
This is just an example. I want to ask your suggestions because I have lots of situations like this. (I am looking for a most efficient way to trim, update some values in the collections)
You can use the distinct method first to get the list of email addresses then use regex to get the names:
db.collection.distinct("email", function(err, result){
var emails = result.map(function(email){
return email.match(/^([^@]*)@/)[1];
});
console.log(emails);
});
With the aggregation framework, MongoDB 3.4 has a $split operator that you can use in conjunction with $arrayElemAt:
db.collection.aggregate([
{
"$group": {
"_id": null,
"emails": {
"$push": {
"$arrayElemAt": [
{ "$split": ["$email", "@"] },
0
]
}
}
}
}
], function(err, result){
if (err) throw err;
console.log(result);
/*
{
"_id" : null,
"emails" : [
"alex",
"elizabeth",
"hannah"
]
}
*/
});