如何在带有数组的对象中使用Mongodb搜索未知路径

时间:2019-05-29 22:54:18

标签: arrays mongodb

我们正在工作的系统将信息存储在json类型字段中,我们目前使用mysql。我们的最新需求之一是搜索与json字段中的条件匹配的信息,但是该字段的问题在于搜索信息的路径未知,因此我们必须执行深度搜索(不确定是否这就是所谓的)。

SELECT JSON_SEARCH(answers, 'one', '%search_criteria%') FROM table 
WHERE id = x

这是可行的,但是由于我们必须搜索整个字段(它可能很大),所以速度非常慢,我们想看看是否可以使用mongodb进行改进。

该字段的格式有些统一,但是路径未知,我们有类似这样的内容:

[{
  "id": 61,
  "questions": {
    "variables": [
      {
        'type_id': 50,
        'label': 'Bye world',
        'answer': false,

      },
      {
        'type_id': 15,
        'label': 'Blah blah',
        'answer': 'Bleh',

      }
    ]
  }
},
{
  "id": 62,
  "questions": {
    "variables": [
      {
        'type_id': 56,
        'label': 'comment',
        'answer': 'Nice comment!',

      },
      {
        'type_id': 15,
        'label': 'Blah blah',
        'answer': 'Bleh',

      }
    ]
  }
},
{
  "id": 63,
  "questions": {
    "variables": [
      {
        'type_id': 15,
        'label': 'Blah blah',
        'answer': 'Bleh!',

      },
      {
        'type_id': 56,
        'label': 'Another comment',
        'answer': 'Bad comment!',

      }
    ]
  }
}]

在json字段中,我们将查找type_id,也许还会寻找标签中的文本,但此刻,对于类型id,有时它会出现,而另一些则不会,并且不会处于同一位置,所以我不确定如何执行搜索。

我以前从未使用过mongobd,所以我不知道我是否接近答案,但是我已经尝试过了:

db.getCollection('collection').find({
  answers : {'0.questions.0.variables.0.type_id' : 56 }
})

在上一个示例中,我知道我正在尝试在特定路径中进行搜索,但是至少我首先尝试了该尝试。

我也看过https://docs.mongodb.com/manual/tutorial/query-arrays/,但我不知道这是否适用。

最后,我们要获得所有匹配的结果,在这种情况下,所有变量中具有type_id = 56的答案。

0 个答案:

没有答案