$ elemMatch中的$或声明

时间:2014-05-18 21:15:57

标签: mongodb mongodb-query nosql

有没有办法在元素匹配中执行$或语句?

我有这个:

opened: {
    $elemMatch: {
        closed: false
        openingEvening: {$lte: currentTime}, 
        closingEvening: {$gte: currentTime},
    }
}

并想将opensMorning添加到l

如何将其扩展为:

opened: {
    $elemMatch: {
        closed: false
        {$or: [
            {openingEvening: {$lte: currentTime}, closingEvening: {$gte: currentTime},},
            {openingMorning: {$lte: currentTime}, closingMorning: {$gte: currentTime}}
         ]
        }
    }
}

是这样的吗?

1 个答案:

答案 0 :(得分:19)

当然可以,只是清理语法,但你基本上已经拥有它了:

{
    "opened": {
        "$elemMatch": {
            "closed": false,
            "$or": [
                {
                    "openingEvening": { "$lte": currentTime  },
                    "closingEvening": { "$gte": currentTime  }
                },
                {
                    "openingMorning": { "$lte": currentTime },
                    "closingMorning": { "$gte": currentTime  }
                }

            ]
        }
    }
}

给出了数据的样本概念:

{
    "_id" : ObjectId("537969cee90c3db84958aa86"),
    "opened" : [
            {
                    "closed" : false,
                    "openingEvening" : 17,
                    "closingEvening" : 22,
                    "openingMorning" : 11,
                    "closingMorning" : 14
            }
    ]
}
{
    "_id" : ObjectId("53796a47e90c3db84958aa87"),
    "opened" : [
            {
                    "closed" : false,
                    "openingMorning" : 13,
                    "closingMorning" : 14
            }
    ]
}

当前时间12将与第一个文档匹配但不匹配第二个文档,但值13将匹配两者。

同时注意到这些是在一个数组内,所以考虑到你的估计目的,你可能想要一个" dayOfWeek"字段也包括在那里