Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

112
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda