首页 > 解决方案 > 如何将排序功能与 $or 和 $and 一起使用?

问题描述

我必须根据一些限制从 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}]
    })

标签: node.jsmongodb

解决方案


你可以先找到你的结果,然后用

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 })

推荐阅读