首页 > 解决方案 > 蒙古数据库。获取其数组字段仅包含查询中的单词的文档

问题描述

是否可以在 mongodb 中找到字段中所有单词都包含在查询中的文档,反之亦然?

伪查询:

{title: 
    {$in: ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]}
}

文档:

{'title': ["brown", "fox"}    #true
{'title': ["lazy", "dog"]}    #true
{'title': ["lazy", "dog", "sleep"]}    #false 'sleep' not in query
{'title': ["brown", "dog"]}    #true
{'title': ["jumps", "quick"]}    #true
{'title': ["smile", "fox"]}    #false 'smile' not in query

标签: mongodbmongodb-query

解决方案


MongoDB 聚合提供了比标准.find方法更多的操作。

接受两个或多个数组并返回一个数组,其中包含出现在每个输入数组中的元素。 https://docs.mongodb.com/manual/reference/operator/aggregation/setIntersection/#exp._S_setIntersection

一旦我们得到交集,我们就会比较数组大小(我假设你的数组不能有重复的值)

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $eq: [
          {
            $size: "$title"
          },
          {
            $size: {
              $setIntersection: [
                "$title",
                [
                  "the",
                  "quick",
                  "brown",
                  "fox",
                  "jumps",
                  "over",
                  "the",
                  "lazy",
                  "dog"
                ]
              ]
            }
          }
        ]
      }
    }
  }
])

Mongo游乐场


推荐阅读