MongoDB: query array for "true" value at index n

So, I have this collection containing a "weekdays" field representing weekdays from Monday to Sunday (checked or unchecked):

  var collection = [

    // work week (Monday to Friday)
    {
      weekdays: [true, true, true, true, true, false, false]
    },

    // weekend
    {
      weekdays: [false, false, false, false, false, true, true]
    },

    // ...

  ];

      

Now, how can I query this collection to find all items from true

for a specified day of the week?

My first attempt was to use something like this:

// $ elemMatch ...

'weekdays[0]': true // Monday

      

But it didn't work. I am out of ideas and would appreciate any help!

+3


source to share


1 answer


you can use this code

db.collectin.find({'weekdays.0' : true})

      



and if you want to check 2 days:

db.collectin.find({$and : 
    [
        {'weekdays.0' : true},
        {'weekdays.1' : true}
    ]
})

      

+2


source







All Articles