MongoDB:统计关联集合中被引用文档的出现次数
Got it, let's walk through how to tally up how many times each book from your Books collection gets referenced in the fav_books arrays of the Users collection. MongoDB's aggregation framework is perfect for this job—here's a step-by-step solution:
Solution Code
db.Users.aggregate([ // Split each user's fav_books array into individual documents { $unwind: "$fav_books" }, // Group by book ID and count how many times each appears { $group: { _id: "$fav_books", count: { $sum: 1 } } }, // Transform results into the key-value format you want { $group: { _id: null, bookCounts: { $push: { k: "$_id", v: { $toString: "$count" } // Convert count to string to match your example } } } }, { $replaceRoot: { newRoot: { $arrayToObject: "$bookCounts" } } } ])
How This Works
Let's break down each stage of the aggregation pipeline:
- $unwind: Takes every user's
fav_booksarray and splits it into separate documents. For example, a user withfav_books: ["123", "124"]becomes two distinct documents—one for each book ID. - First $group: Groups all those unwound documents by book ID, then uses
$sum: 1to count how many times each ID shows up across all users. - Second $group: Collects all the count entries into an array of
{k: bookId, v: count}objects. We use$toStringhere to convert the numeric count to a string, matching your desired output format. - $replaceRoot: Converts that array of key-value pairs into a single object using
$arrayToObject, then sets that object as the final result document.
Expected Output
Running this aggregation will return exactly the format you're looking for:
{ "123": "3", "124": "2", "125": "2" }
If you ever wanted to include book names from the Books collection too, you could add a $lookup stage after the first $group to join the two collections, then adjust the final transformation to include the name. But for your current requirements, the above code should work flawlessly.
内容的提问来源于stack exchange,提问作者Siraj ul Haq

