多个where语句mongodb

时间:2014-04-25 17:33:36

标签: mysql node.js mongodb mongoose mongodb-query

好的,所以我很难与mongodb一起来自MySQL,我遇到了麻烦 编写查询以获取我的数据。我的数据库看起来像这样:

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}
        ]

我想要完成的是以下内容: 我有一个名为:currendTime的变量,我有一个变量,我将currentDay作为全名。所以变量currentDay包含" Friday"。

我想要实现的是搜索currentDay等于星期五的当天以及当前时间高于"来自"和currentTime低于"直到"

有人能帮助我吗?

更新 这就是我到目前为止所做的:

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);
        });

1 个答案:

答案 0 :(得分:0)

您需要将所有数组元素字段组合在一起以匹配$elemMatch对象:

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);
    });

如果您只想要匹配的元素,请在find来电中添加以下字段投影参数:

{ 'opened.$': 1 }