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

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

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 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