$或查询多个参数

时间:2016-09-08 15:02:22

标签: mongodb mongoose

我试图实现以下目标

Filter

用mongoose:

InStr

此查询似乎与所有给定条件都不匹配。我错过了SELECT * FROM users WHERE (_currentMatch = null AND unregistrated = false AND gender = 'male' AND lastMatchTime < dateMale) OR (_currentMatch = null AND unregistrated = false AND gender = 'female' AND lastMatchTime < dateFemale); 吗?

1 个答案:

答案 0 :(得分:3)

看到前两个条件(_currentMatch = null AND unregistrated = false)在两个OR子句中都重复,您的SQL查询就可以 被重写为:

SELECT *
FROM users
WHERE   
    _currentMatch = null 
    AND unregistrated = false 
    AND gender in ('female', 'male')

等效的mongo查询如下:

User.find({
    "_currentMatch": null,
    "unregistrated": false,
    "gender": { "$in": ["female", "male"] }
})

- 更新 -

SELECT *
FROM users
WHERE   (_currentMatch = null AND
        unregistrated = false AND
        gender = 'male' AND
        lastMatchTime < dateMale)
OR      (_currentMatch = null AND
        unregistrated = false AND
        gender = 'female' AND
        lastMatchTime < dateFemale);

可以重写为

User.find({
    "_currentMatch": null,
    "unregistrated": false,
    "$or": [
        { "gender": "female", "lastMatchTime": { "$lt": dateFemale } },
        { "gender": "male", "lastMatchTime": { "$lt": dateMale } }
    ]
})