Arrays Mongoose排序并获取非重复值
我是所有NodeJS/MongoDB/Mongoose技术中的新手,我试图从数组中获取不重复的值,并按两个值对数据进行排序位置和在创建 这是密码Arrays Mongoose排序并获取非重复值,arrays,node.js,mongodb,mongoose,Arrays,Node.js,Mongodb,Mongoose,我是所有NodeJS/MongoDB/Mongoose技术中的新手,我试图从数组中获取不重复的值,并按两个值对数据进行排序位置和在创建 这是密码 Temperature.find().sort({'location': -1,'created_at': -1}).exec(function(err, results){ res.json(results); }); 如何从数组中获取第一个非重复值 这是阵列: [ { temperature: '24', humidity:
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,
},
]
您需要使用聚合框架
$group
打开位置
键,使用$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")
}
}
非常感谢您的解释和示例!查询是否没有按您预期的方式工作?让我知道查询没有排序。添加了输出。输出与预期输出匹配。您在创建的
类型必须是日期
而不是字符串
。这是我能看到的唯一一件会把分类搞砸的事情。