简体   繁体   English

如何根据字符串的引用数组是否有共同的项目来查找包含字符串数组的文档?

[英]How to find a document with an array of strings based on if it has items in common with a reference array of string?

Given a reference array of strings: ["Comedy", "Horror", "Romance"] , I would like to query a Movie model with this schema:给定一个参考字符串数组: ["Comedy", "Horror", "Romance"] ,我想使用以下模式查询Movie model:

const MovieSchema = new Schema({
    _id: {
        type: Types.ObjectId,
        required: true
    },
    title: {
        type: String,
        required: true
    },
    categories: [{ type: String }],
});

Such that I will get results where I will get Movie s with categories in common with the reference array, sorted by the amount of elements it has in common with the reference array.这样我将得到结果,其中我将获得具有与参考数组相同类别的Movie ,并按其与参考数组共有的元素数量排序。 For example:例如:

[
    {
        _id: "57",
        title: "Sample Movie A",
        categories: ["Comedy", "Horror", "Romance", "Family"]
    },
    {
        _id: "92",
        title: "Sample Movie B",
        categories: ["Comedy", "Romance", "Family", "Coming of Age"]
    }
]

Note that Movie A is the first in the results because it has 3 items in common with the reference array while Movie B only has 2 items in common.请注意,电影 A 是结果中的第一个,因为它与参考数组有 3 个共同项,而电影 B 只有 2 个共同项。

How can I achieve this query using Mongoose 5.11.16?如何使用 Mongoose 5.11.16 实现此查询?

You could use $setIntersection to get a count of matching elements, add the resulting array-size as a new field to each document and and then sort by this field.您可以使用$setIntersection获取匹配元素的计数,将生成的数组大小作为新字段添加到每个文档,然后按此字段排序。

You could then extend the query to filter matches with a count greater than 0 and remove the categoryCount from the output, eg然后,您可以扩展查询以过滤计数大于0的匹配项,并从 output 中删除categoryCount ,例如

Movie.aggregate([
  {
    "$addFields": {
      "categoryCount": {
        $size: {
          $setIntersection: [
            [
              "Comedy",
              "Horror",
              "Romance"
            ],
            "$categories"
          ]
        }
      }
    }
  },
  {
    "$match": {
      categoryCount: {
        $gt: 0
      }
    }
  },
  {
    "$sort": {
      categoryCount: -1
    }
  },
  {
    "$project": {
      categoryCount: 0
    }
  }
])

Example on mongoplayground: https://mongoplayground.net/p/ZlUNfB82FRK mongoplayground 上的示例: https://mongoplayground.net/p/ZlUNfB82FRK

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM