如何与$ or和$ and一起使用排序功能?

时间:2018-08-21 06:44:33

标签: node.js mongodb

我必须根据一些限制从MongoDB中获取数据,并且应该按日期和时间进行排序。我已经尝试过下面的代码,但是运气不好。

    var startDate = new Date();
    var  endDate = new Date();
    endDate.setDate(endDate.getDate() - 365);
    collections.find({
        $and: [{
            $or: [{
                "times.0.date": {
                    $gte: endDate,
                    $lte: startDate
                }
            }, {
                "times.date": {
                    $gte: endDate,
                    $lte: startDate
                }
            }]
        }, {
            "user_id": parseInt(user._id)
        }],
        $sort: [{startDate: -1}]
    })

2 个答案:

答案 0 :(得分:1)

您可以先找到结果,然后使用

对其进行排序
collections.find({
    $and: [{
        $or: [{
            "times.0.date": {
                $gte: endDate,
                $lte: startDate
            }
        }, {
            "times.date": {
                $gte: endDate,
                $lte: startDate
            }
        }]
    }, {
        "user_id": parseInt(user._id)
    }]
}).sort({ "times.date": -1 })

答案 1 :(得分:0)

find()方法之后使用 sort()方法,而不是在find方法内部使用  $or, $and内查找。

db.bios.find({$and: [{$or: [{..},{..}]}]}).sort( { name: 1 } )