使用mongoose

时间:2018-04-03 14:17:59

标签: node.js mongodb mongoose

鉴于此文件:

"_id" : ObjectId("5a4ea040825de6c0bbbcc810"),
"onOpened" : [ 
        {
            "createdOn" : ISODate("2018-01-04T21:46:56.756Z"),
            "_id" : ObjectId("5a4ea0d0825de6c0bbbcc828")
        }, 
        {
            "createdOn" : ISODate("2018-01-04T21:57:24.939Z"),
            "_id" : ObjectId("5a4ea344a7513e0d27642494")
        }, 
        {
            "createdOn" : ISODate("2018-01-05T18:27:26.839Z"),
            "_id" : ObjectId("5a4fc38e62a06a8cced22657")
        }]
"onSynched" : [ 
        {
            "createdOn" : ISODate("2018-01-04T21:46:56.756Z"),
            "_id" : ObjectId("5a4ea0d0825de6c0bbbcc828")
        }, 
        {
            "createdOn" : ISODate("2018-01-04T21:57:24.939Z"),
            "_id" : ObjectId("5a4ea344a7513e0d27642494")
        }, 
        {
            "createdOn" : ISODate("2018-01-05T18:27:26.839Z"),
            "_id" : ObjectId("5a4fc38e62a06a8cced22657")
        }]

我正在尝试在MongoDB / Mongoose中进行aggregate查询,以便我只能选择给定日期范围内的元素。我试过这个:

module.exports.getWorksetStats = function (req, res) {
    var id = req.params.id;
    var from = new Date(req.query.from);
    var to = new Date(req.query.to);
    HealthRecords
        .aggregate(
            [
                {$match: {_id: id}},
                {$project: {
                    'onOpened': {$filter: {
                        input: '$onOpened',
                        as: 'item',
                        cond: {$and: [
                            {$gte: ['$$item.createdOn', from]},
                            {$lte: ['$$item.createdOn', to]}
                        ]}
                    }}
                }}
            ]
        ).exec(function (err, response){
            var result = {
                status: 200,
                message: response
            };
            if (err){
                result.status = 500;
                result.message = err;
            } else if (!response){
                result.status = 404;
                result.message = err;
            }
            res.status(result.status).json(result.message);
        });
};

不幸的是,这似乎是返回一个空数组。谁能想到我在这里做错了什么?

此外,目标是在一个查询中做一些事情,但我想我可以从这开始。这个想法真的是: 1.按日期范围过滤onOpened, 2. onSynched按日期范围过滤, 3.和另一个集合但$slice: -1

我正在使用MongoDB 3.4.7和Mongoose 4.5.5。

1 个答案:

答案 0 :(得分:1)

试试这个

db.getCollection('TEST').aggregate([{
        $match: {
            _id: id
        }
    },
    {
        $project: {
            onOpened: {
                $filter: {
                    input: "$onOpened",
                    as: "item",
                    cond: {
                        $gte: ['$$item.createdOn', from],
                        $lte: ['$$item.createdOn', to]
                    }
                }
            },
            onSynched: 1
        }
    }
]);