我有一个集合名称为“sensors”的数据库,它看起来像这样:
{ "_id" : ObjectId("5d4d27a7e1f2cf1d7cba1fe3"), "type" : "thermometer", "value" : 23, "createdAt" : ISODate("2019-08-09T07:58:31.698Z"), "updatedAt" : ISODate("2019-08-09T07:58:31.698Z"), "__v" : 0 }
{ "_id" : ObjectId("5d4d27a7e1f2cf1d7cba1fe4"), "type" : "hygrometer", "value" : 74, "createdAt" : ISODate("2019-08-09T07:58:31.739Z"), "updatedAt" : ISODate("2019-08-09T07:58:31.739Z"), "__v" : 0 }
{ "_id" : ObjectId("5d4d27a8e1f2cf1d7cba1fe5"), "type" : "thermometer", "value" : 25, "createdAt" : ISODate("2019-08-09T07:58:32.551Z"), "updatedAt" : ISODate("2019-08-09T07:58:32.551Z"), "__v" : 0 }
我想要做的是查询最后两个文档,温度计和湿度计,然后检查每个文档的值。然后根据我使用 $match 标记设置的条件,我执行我想要的任何操作。
MongoClient.connect('mongodb://localhost', { useNewUrlParser: true }, function (err, client) {
if (err) throw err;
var db = client.db('mongodb');
db.collection('sensors').aggregate(
[
{ $sort: { _id: -1 } },
{ $limit: 1 },
{
$match: {"type": "hygrometer", "value": { "$gt": 60 } }
}
]
).toArray(function(err, item) {
if(err) console.log('error');
if(item.length > 0) console.log('Dehumidifier ON');
else console.log('Dehumidifier OFF');
});
这只是最后一个数据(湿度计)的实现,但我应该如何检查最后两个文档,然后对温度计执行单独的操作,例如“AC ON/OFF”?我在想以某种方式让它检查 item.type == "thermometer"何时执行某些操作,但 item.type 语法似乎不起作用
最佳答案
请尝试以下查询:
db.aggtest.aggregate([
{ $sort: { _id: -1 } },
{ $limit: 2 },
{$match: { $or: [ {"type": "hygrometer", "value": { "$gt": 60 }}, {"type": "thermometer"} ]}}
])
关于mongodb - 如何使用mongodb聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57865490/