Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

106
Views
Is it possible to update value in the collection in the query?

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)

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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"
            ]
        }   
    */
});
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!