You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

技术求助:$setIntersection匹配计数及MongoDB电影num_favs字段计算

Solution to Your MongoDB Aggregation Questions

Let’s walk through each of your requirements with clear, actionable MongoDB aggregation pipeline steps:

1. Get Match Count with $setIntersection

$setIntersection returns the common elements between two arrays, and pairing it with $size gives you the count of those matching elements.

Suppose you have a collection where each document has a target_array (your existing set) and a search_array (the new array you want to check against). Here’s how to calculate the match count:

db.yourCollection.aggregate([
  {
    $addFields: {
      match_count: {
        $size: {
          $setIntersection: ["$target_array", "$search_array"]
        }
      }
    }
  }
])
  • $setIntersection: Compares the two arrays and returns only elements present in both.
  • $size: Takes the resulting intersection array and returns its length (the number of matches).

2. Calculate num_favs for Qualifying Movies

First, we’ll filter the movies that meet your criteria, then compute the num_favs field by counting how many cast members are in your "favorite people" list.

Assuming:

  • Your favorite people are stored in an array (e.g., ["Tom Hanks", "Meryl Streep"])
  • The movie collection has fields: country (for US release), tomatoes.viewer.rating, and cast (array of cast members)

Here’s the aggregation pipeline:

const favoriteCast = ["Tom Hanks", "Meryl Streep"]; // Replace with your actual favorite list

db.movies.aggregate([
  // Step 1: Filter movies that meet the criteria
  {
    $match: {
      "country": "USA",
      "tomatoes.viewer.rating": { $gte: 3 }
    }
  },
  // Step 2: Add the num_favs field
  {
    $addFields: {
      num_favs: {
        $size: {
          $setIntersection: ["$cast", favoriteCast]
        }
      }
    }
  }
])
  • $match: Narrows down the documents to only US-released movies with a Tomato viewer rating of 3 or higher.
  • $setIntersection: Finds overlapping elements between the movie’s cast array and your favoriteCast list.
  • $size: Counts those overlapping elements to get the num_favs value.

If your favorite cast list is stored in another collection instead of a variable, you can use $lookup to fetch it first, then proceed with the intersection calculation. Feel free to ask for help with that variation!

内容的提问来源于stack exchange,提问作者Sampath chary

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:00:10