技术求助:$setIntersection匹配计数及MongoDB电影num_favs字段计算
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, andcast(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’scastarray and yourfavoriteCastlist.$size: Counts those overlapping elements to get thenum_favsvalue.
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

