如何在MongoDB中找到子文档中的元素

如何在MongoDB中找到子文档中的元素,mongodb,Mongodb,如果我在MongoDB中有一个数据,如下所示,有2个文档,每个文档都有传感器的子文档。如何获取MongoDB中节点ID为1的传感器列表 { "name": "Site 1", "sensors": [ { "nodeId": 1, "value": "23" }, { "nodeId": 1, "value": "34" }, { "nodeId": 2, "value": "66" } ] } { "name": "Site 2", "sensor

如果我在MongoDB中有一个数据,如下所示,有2个文档,每个文档都有传感器的子文档。如何获取MongoDB中节点ID为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" }
  ]
}
预期产量


如果您有传感器模式和模型,如果您使用的是mongoose:

sensors.find({sensors : {'$ne': null }}, function(err, docs){
                if(err)
                    console.log(err);
                else
                    res.end(JSON.stringify({sensors : docs}, null, 3));
});
如果您在项目中使用运算符,如下所示:

db.collectionName.find({"sensors":{"$elemMatch":{"nodeId":1}}},{"sensors.$":1}).pretty()
由于以下$operator的限制,它只返回第一个匹配的数组值

由于查询文档中只能显示一个数组字段,因此如果数组包含文档,要指定这些文档的多个字段的条件,请使用$elemMatch运算符

如果得到预期结果,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()
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()