根据另一个文档过滤.find()会返回[]

时间:2015-10-14 22:17:00

标签: mongodb mongodb-query

以下是我对查询的尝试AFTER Sergiu Zaharie的回答发布在下面:

    db.collection('users').find({_id:ObjectID('561f0cbd3ed5b852e95cab6a')}).limit(1).toArray(function(error, result) {
        if((!error) && (result[0] !== undefined) && result.length) {
            var user = result[0];

            console.log("User ID: ", user._id);
            console.log("Blocked users: ", user.blocked_users);
            console.log("passed quizzes: ", user.passed_quizzes);
            console.log("failed quizzes: ", user.failed_quizzes);

            db.collection('users').find({
                $and: [
                    { _id: { $in: [user._id] } },
                    { blocked_users: { $nin: [user.blocked_users] } },
                    { passed_quizzes: { $nin: [user.passed_quizzes] } },
                    { failed_quizzes: { $nin: [user.failed_quizzes] } }
                ]
            }).toArray(function(error, doc) {
                console.log("Results: ", doc);
            });
        }
    });

表格中有三个用户,一个用ObjectID('561f0cbd3ed5b852e95cab6a')(我),一个用ObjectID('561f0bbaff803840e917568d')(michael),另一个用ObjectID('561f0b68d83c293fe960a25d')(托马斯)。

上面执行的查询应该返回包含ObjectID('561f0bbaff803840e917568d')(Michael)的帐户,而不是查询返回[] 0个结果。

数据输出:

User ID:  561f0cbd3ed5b852e95cab6a
Block users:  [ 561f0b68d83c293fe960a25d ]
passed quizzes:  []
failed quizzes:  []
Results:  []

这将使查询执行:

db.collection.find({ 
    $and: [
        // Void out myself, because I'm looking for other people.
        { _id: { $nin: [ ObjectID('561f0cbd3ed5b852e95cab6a') ] } },
        // Void out blocked users, because I blocked them.
        { blocked_users: { $nin: [ObjectID('561f0b68d83c293fe960a25d')] } },
        // More array based filtering: (Blank arrays, shouldn't matter right now)

        { passed_quizzes: { $nin: [] } },
        { failed_quizzes: { $nin: [] } }
    ]
});

如上所述,这为find()语句返回ObjectID('561f0bbaff803840e917568d')的文档留出了空间。因为它没有根据上述要求进行过滤。

1 个答案:

答案 0 :(得分:2)

尝试此查询:

db.collection.find(
    { [
        {_id: { $nin: [id] }},
        { "settings.min_rating": { $lt: rating }},
        { "settings.max_rating": { $gt: rating }}, 
        { blockedUsers: { $nin: [id] }}, 
        { discoveredUsers: { $nin: [id] }}  
      ] 
    }
)