Mongoose排序并获得非重复值

时间:2017-01-26 19:41:34

标签: arrays node.js mongodb mongoose

我在所有NodeJS / MongoDB / Mongoose技术中都是新的,我试图从数组中获取非重复值,并且我按两个值对数据进行排序; 位置 created_at

这是代码

Temperature.find().sort({'location': -1,'created_at': -1}).exec(function(err, results){
  res.json(results);
});

如何从数组中获取第一个非重复值?

这是数组:

[ { 
    temperature: '24',
    humidity: '15',
    location: 'Camara4',
    created_at: 2017-01-24T21:40:21.552Z
   },
  { 
    temperature: '23',
    humidity: '15',
    location: 'Camara4',
    created_at: 2017-01-24T01:18:26.328Z
     },
  { 
    temperature: '15',
    humidity: '12',
    location: 'Camara3',
    created_at: 2017-01-26T18:53:34.447Z,
     },
  { 
    temperature: '36',
    humidity: '11',
    location: 'Camara3',
    created_at: 2017-01-24T21:41:07.094Z,
    },
  { 
    temperature: '35',
    humidity: '11',
    location: 'Camara3',
    created_at: 2017-01-24T21:41:03.092Z,
   }
]

我希望:

[ { 
    temperature: '24',
    humidity: '15',
    location: 'Camara4',
    created_at: 2017-01-24T21:40:21.552Z
   },
  { 
    temperature: '15',
    humidity: '12',
    location: 'Camara3',
    created_at: 2017-01-26T18:53:34.447Z,
    },
]

1 个答案:

答案 0 :(得分:1)

您需要使用聚合框架。

使用$group运算符在location键上

$first从每个组中的排序顺序中选择第一个值。

Temperature.aggregate({
    "$sort": {
        'location': -1,
        'created_at': -1
    }
}, {
    $group: {
        "_id": "$location",
        "result": {
            "$first": "$$ROOT"
        }
    }
}).exec(function(err, results) {
    res.json(results);
});

输出:

{
        "_id" : "Camara4",
        "result" : {
                "temperature" : "24",
                "humidity" : "15",
                "location" : "Camara4",
                "created_at" : ISODate("2017-01-24T21:40:21.552Z")
        }
}
{
        "_id" : "Camara3",
        "result" : {
                "temperature" : "15",
                "humidity" : "12",
                "location" : "Camara3",
                "created_at" : ISODate("2017-01-26T18:53:34.447Z")
        }
}