Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: query Array for 'true' value at index n

So I have this collection containing a field "weekdays" representing weekdays Monday-Sunday (checked or not checked):

  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 that has true for a specified weekday?

My first attempt was to use something like this:

// $elemMatch...

'weekdays[0]': true // Monday

But it did not seem to work. I'm out of ideas atm and would appreciate any help!

like image 303
Mickel Avatar asked Mar 04 '26 08:03

Mickel


1 Answers

you can use this code

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

and if you want check 2 days:

db.collectin.find({$and : 
    [
        {'weekdays.0' : true},
        {'weekdays.1' : true}
    ]
})
like image 55
2 revs, 2 users 67% Avatar answered Mar 06 '26 23:03

2 revs, 2 users 67%