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

260
Vistas
How to query MongoDb documents using the indices of embedded arrays

I am trying to learn how to use mongo queries to reach deep into a data tree. Specifically, I'm trying to remove the object below {"object": 'to remove'}

{
    "_id" : ObjectId("7840f22736341b09154f7ebf"),
    "username" : "nmay",
    "fname" : "Nate",
    "lname" : "May",
    "data" : [ 
        {
            "monthNum" : 1,
            "year" : 2016,
            "days" : [ 
                {
                    "date" : "2016-01-01T06:00:00.000Z",
                    "type1" : [],
                    "type2" : []
                }, 
                {
                    "date" : "2016-01-02T06:00:00.000Z",
                    "type1" : [
                       {"object": 'to remove'}
                    ],
                    "type2" : []
                }
            ]
        }
    ]
}

so far I know how to query for the user _id, but I'm not sure how to remove the desired object using the indices in each array. In this example I want to remove data[0].days[1].type1[0]

Here is the query that I have so far:

app.delete('/user/:id/data/:monthIndex/days/:dayIndex/type1/:type1Index', function (req, res, next) {
  var monthIndex = parseInt(req.params.monthIndex); // these console the value properly
  var dayIndex = parseInt(req.params.dayIndex); // -1 is applied to the parameter to translate to array position
  var type1Index = parseInt(req.params.type1Index);

  db.users.update(
     { _id: mongojs.ObjectId(req.params.id) },
     { $pull: data.monthIndex.days.dayIndex.type1.type1Index }
   );
}

It gives me the error

ReferenceError: data is not defined

Can someone demonstrate how I can pass this query my index parameters to remove the desired object?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Unfortunately, there is no way to remove an array element by its numerical index with a single operation in MongoDB. In order to do this, you need to unset desired element(s) first, and remove the resulting null-valued fields afterwards.

Your code should look something like this:

db.users.update(
    { _id : mongojs.ObjectId(req.params.id) },
    { $unset : { 'data.0.days.1.type1.0' : 1 } }
);
db.users.update(
    { _id : mongojs.ObjectId(req.params.id) },
    { $pull : { 'data.0.days.1.type1' : null } }
);

Edit by @bob: to pass in the parameters you have to build the query string, which is ugly:

var unset = {};
unset['$unset'] = {};
unset.$unset['data.' + req.params.monthIndex + '.days.' + req.params.dayIndex + '.foods.' + req.params.foodIndex] = 1;

db.users.update( { _id : mongojs.ObjectId(req.params.id) }, unset );

var pull = {};
pull['$pull'] = {};
pull.$pull['data.' + req.params.monthIndex + '.days.' + req.params.dayIndex + '.foods'] = null;

db.users.update( { _id : mongojs.ObjectId(req.params.id) }, pull );
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