Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

111
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda