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

MongoDB:统计关联集合中被引用文档的出现次数

Counting Book References in MongoDB Users Collection

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_books array and splits it into separate documents. For example, a user with fav_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: 1 to 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 $toString here 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:12:52