使用AND和OR进行Meteor MongoDB查询

时间:2017-03-20 08:43:53

标签: mongodb meteor mongodb-query

我想在mongo db中查询一下这样的SQL:

Select * from Users 
where familyId =@X and (isDeleted =false or isDeleted is null)

我已经有了第一个条件,我不知道如何将它与And-Or混合

var myMembers = Meteor.users.find({ "profile.family_id":      Meteor.user().profile.family_id });

怎么可能?

1 个答案:

答案 0 :(得分:6)

您可以使用 $and 运算符明确查询:

var family_id = Meteor.user().profile.family_id,
    myMembers = Meteor.users.find({ 
        "$and": [
            { "profile.family_id": family_id },
            {
                "$or": [
                    { "isDeleted": false },
                    { "isDeleted": null } /* or { "isDeleted": { "$exists": false } } */
                ]
            }
        ]
    });

或通过指定以逗号分隔的表达式隐式:

var family_id = Meteor.user().profile.family_id,
    myMembers = Meteor.users.find({ 
        "profile.family_id": family_id,
        "$or": [
            { "isDeleted": false },
            { "isDeleted": null } /* or { "isDeleted": { "$exists": false } } */
        ]
    });

注意:要检查字段是否存在,您可以将$exists运算符用作{ "isDeleted": { "$exists": false } },因为{ isDeleted : null } query匹配的是要么包含值为null的isDeleted字段,要么包含isDeleted字段。