MongoDB查询以在没有字段名称的嵌套数组中搜索文本

时间:2019-12-05 15:07:51

标签: mongodb mongodb-query

我有一个包含数百个文档的集合,其中包含我们的AWS EC2实例信息。我需要一个查询来搜索包含特定IP地址(例如:1.2.3.7)的文档。 IP信息位于没有字段名称的数组中。

示例文档:

{"generated": "01-Dec-2019","data":[
["default","Jenkins1","running","us-east-1a","1.2.3.4","10.1.2.3"],
["default","Jenkins2","running","us-east-1a","1.2.3.5","10.1.2.4"]
]}

{"generated": "02-Dec-2019","data":[
["default","Jenkins1","running","us-east-1a","1.2.3.4","10.1.2.3"],
["default","Jenkins3","running","us-east-1a","1.2.3.6","10.1.2.5"]
]}

{"generated": "03-Dec-2019","data":[
["default","Jenkins1","running","us-east-1a","1.2.3.4","10.1.2.3"],
["default","Jenkins4","running","us-east-1a","1.2.3.7","10.1.2.6"]
]}

{"generated": "04-Dec-2019","data":[
["default","Jenkins6","running","us-east-1a","1.2.3.9","10.1.2.8"],
["default","Jenkins5","running","us-east-1a","1.2.3.8","10.1.2.7"]
]}

1 个答案:

答案 0 :(得分:0)

您可以使用嵌套$elemMatch来检查一个数组(该数组是另一个数组的元素)是否包含您要查找的IP:

db.collection.find({
  data: {
    $elemMatch: {
      $elemMatch: {
        $in: ["1.2.3.7"]
      }
    }
  }
})

您可以在此playground中运行此查询。