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

252
Views
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 answers
Answer question

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