0

I am trying to query a nested array based on indexes from my mongodb database but I am having a difficult time building my query. My question is if it is possibly to build a mongodb query for nested arrays like you can natively in JavaScript

workouts[0][0].exercises[0] 

I need to be able to pass in a variable for each [0] above so that I can update or find each specific exercise in each specific week. I know from reading the docs and other questions related to nested arrays is that mongodb has a difficult time doing this if I read correctly. If that is the case is there a better way to structure my data so that it would be easier to query with mongodb or do I just have to grab the entire object and filter through it myself with JavaScript?

{
  "_id" : "Qr8bHSm2tHunvWdmY",
  "owner" : "xaSeX4yXbiXJZ8XZp",
  "name" : "Fourth Program",
  "weeks" : "1",
  "workouts" : [ // array to hold each week
    [ // individual week array
      {
        "day" : 1,
        "exercises" : [
          {
            "exercise" : "Bench press",
            "weight" : "185",
            "reps" : "8",
            "sets" : "4"
          },
          {
            "exercise" : "Shoulder press",
            "weight" : "135",
            "reps" : "8",
            "sets" : "4"
          }
        ]
      },
      {
        "day" : 2,
        "exercises" : [
          {
            "exercise" : "Sqaut",
            "weight" : "225",
            "reps" : "10",
            "sets" : "3"
          },
          {
            "exercise" : "Deadlift",
            "weight" : "300",
            "reps" : "5",
            "sets" : "3"
          }
        ]
      }
    ]
  ]
}
Jose
  • 1,959
  • 20
  • 21
  • 1
    can you try this : ```workouts[0][0].exercises[0] ``` of javascript will converted to ```workouts.0.0.exercises.0``` in mongo query. – Dhaval Chaudhary Mar 15 '18 at 03:43
  • Thanks man that really helps, whats really throwing me off is that the mongodb query only accepts key:value pairs so what I wanted to do was ExercisesCollection.find({ 'workouts.0.0.exercises.0' }) and have that return the array that I am looking for but it won't work that way unless I use the aggregation framework like referenced in this answer https://stackoverflow.com/questions/36229123/return-only-matched-sub-document-elements-within-a-nested-array. I'll probably just return the entire workouts array and filter it on the front end. – Jose Mar 16 '18 at 13:05
  • whatever suits you :) – Dhaval Chaudhary Mar 18 '18 at 08:48

0 Answers0