如果我在MongoDB中有一个数据如下,有2个文件,每个文件都有传感器子文件。如何获取MongoDB中 nodeId 为1的传感器列表?
{
"name": "Site 1",
"sensors": [
{ "nodeId": 1, "value": "23" },
{ "nodeId": 1, "value": "34" },
{ "nodeId": 2, "value": "66" }
]
}
{
"name": "Site 2",
"sensors": [
{ "nodeId": 2, "value": "78" },
{ "nodeId": 2, "value": "99" },
{ "nodeId": 2, "value": "11" },
{ "nodeId": 1, "value": "45" }
]
}
预期输出
{
"sensors": [
{ "nodeId": 1, "value": "23" },
{ "nodeId": 1, "value": "34" },
{ "nodeId": 1, "value": "45" }
]
}
答案 0 :(得分:0)
如果您有传感器架构和模型(如果您使用猫鼬):
sensors.find({sensors : {'$ne': null }}, function(err, docs){
if(err)
console.log(err);
else
res.end(JSON.stringify({sensors : docs}, null, 3));
});
答案 1 :(得分:0)
如果你在项目中使用了$运算符,如下所示:
db.collectionName.find({"sensors":{"$elemMatch":{"nodeId":1}}},{"sensors.$":1}).pretty()
由于$
运算符
由于查询文档中只能出现一个数组字段,如果数组包含文档,要在这些文档的多个字段中指定条件,请使用$ elemMatch运算符。
如果你$aggregation然后得到了预期的结果,mongo聚合查询如下:
db.collectionName.aggregate({
"$unwind": "$sensors" // first unwind all sensors array
}, {
"$match": {
"sensors.nodeId": 1 //macth your criteria
}
}, {
"$group": {
"_id": "$sensors.nodeId", // group matchinng criteria
"sensors": {
"$push": "$sensors"
}
}
}, {
"$project": {
"_id": 0,
"sensors": "$sensors"
}
}).pretty()