在集合中查找具有多个元素匹配的查询

时间:2016-12-14 15:00:16

标签: mongodb

我在尝试查找适当的查询以查找表中的数据时遇到了一些问题,我已经尝试过使用elementMatch,在另一个问题中阅读了很多内容。尝试$ redact但我只能获得2个文件中的1个。我做错了什么?为什么我只得到一个? 我有这个文件

   {
"_id" : "dff26f9c-350b-4bd5-bc62-62c19f21100c",
"sensorId" : "123456",
"sensorModel" : "LOOP",
  "attachments" : [ 
    {
        "type" : "StructAttachment",
        "data" : "STRUCT DATA"
    }, 
    {
        "type" : "BlobAttachment",
        "data" : { "$binary" : "QkxPQl9EQVRB", "$type" : "00" }
    }, 
    {
        "type" : "otherData",
        "data" : { "$binary" : "QkxPQl9EQVRB", "$type" : "00" }
    }
]

}

我正在寻找的结果是

   {
"_id" : "dff26f9c-350b-4bd5-bc62-62c19f21100c",
"sensorId" : "123456",
"sensorModel" : "LOOP",
  "attachments" : [ 
    {
        "type" : "StructAttachment",
        "data" : "STRUCT DATA"
    }, 
    {
        "type" : "BlobAttachment",
        "data" : { "$binary" : "QkxPQl9EQVRB", "$type" : "00" }
    }
]

}

我想过滤_id和attachment.type(" structAttachment"或" blobAttachment")

1 个答案:

答案 0 :(得分:1)

$filter$setIsSubset一起使用,如下所示:

db.collectionName.aggregate({
  "$project": {
    "sensorId": 1,
    "sensorModel": 1,
    "attachments": {
      "$filter": {
    "input": "$attachments",
    "as": "el",
    "cond": {
      "$setIsSubset": [
        ["$$el.type"],
        ["StructAttachment", "BlobAttachment"]
      ]
    }
      }
    }
  }
}).pretty()