Ok so i'm having a hard time with mongodb, coming from MySQL i'm having trouble writing the queries to get my data. My Database looks like this:

opened: [
            {day: "Monday", from: 64800, till: 79200},
            {day: "Thuesday", from: 64800, till: 79200},
            {day: "Wednesday", from: 64800, till: 79200},
            {day: "Thursday", from: 64800, till: 79200},
            {day: "Friday", from: 64800, till: 79200},
            {day: "Saturday", from: 64800, till: 79200},
            {day: "Sunday", from: 64800, till: 79200}
        ]

What i'm trying to accomplish is the following: I have a variable named: currendTime and I have a variable where I have the currentDay as a full name. So the variable currentDay contains "Friday".

What I want to achieve is to search for the day where currentDay is equal to Friday and where current time is higher than "from" and currentTime is lower than "till"

Could somebody help me?

Update this is what i have so far:

db.collection('test', function(err, collection) {
    collection.find(
        {
            opened: {$and: [{$elemMatch: {day: weekDay}}, 
                            {from: {$lt: currentTime}},
                            {till: {$gt: currentTime}}]}
            }).toArray(function(err,items) {
            res.send(items);
        });
有帮助吗?

解决方案

You need to combine all the array element fields to match against into the $elemMatch object:

db.collection('test', function(err, collection) {
    collection.find({
        opened: {
            $elemMatch: {
                day: weekDay, 
                from: {$lt: currentTime},
                till: {$gt: currentTime}
            }
        }
    }).toArray(function(err,items) {
        res.send(items);
    });

If you just want that matched element, include the following field projection parameter to your find call:

{ 'opened.$': 1 }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top