Mongodb。获取其数组字段仅包含查询词的文档

时间:2020-02-14 21:54:40

标签: mongodb mongodb-query

在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

1 个答案:

答案 0 :(得分:1)

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"
                ]
              ]
            }
          }
        ]
      }
    }
  }
])

MongoPlayground