返回子文档属性的最小值和最大值

时间:2013-10-07 13:49:23

标签: mongodb mongoose

假设我有以下集合:

{
    "title": "foo1",
    "description: "bar1",
    "foobars": [
        {
            "title": "foobar1",
            "time": {
                "$date": "2013-10-04T19:53:54.714Z"
            }
        },
        {
            "title": "foobar2",
            "time": {
                "$date": "2013-10-06T19:53:54.714Z"
            }
        },
    ]
}

如何查询(使用Mongoose)查找所有文档的所有time的最小和最大foobars值。从文档中看起来像是这样的方式,但这不起作用:

FooModel.aggregate({ $group: { _id: null, maxTime: { $max: '$foobars.time' }}}, callback);

1 个答案:

答案 0 :(得分:3)

分组之前

$unwind foobars

FooModel.aggregate(
    { $unwind: '$foobars' },
    { $group: { _id: null, maxTime: { $max: '$foobars.time' }}}, 
    callback);