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

MongoDB基于单字段输出的统计计数:进阶需求咨询

How to Do Single-Field Count Statistics in MongoDB Aggregation

Got it, let's walk through how to get that single-field count stat you need. You already have the average beds query down, so we'll build on that aggregation framework knowledge.

Core Idea: Group by Your Target Field & Count

The key is using the $group stage with your chosen field as the _id (the grouping key), then using $sum: 1 to count how many documents fall into each group. Here are common use cases with your listings data:


1. Count Listings by Building Type (Group by build field)

If you want to know how many New York listings are concrete, wood, asphalt, etc., use this query:

db.listings.aggregate([
  // First, filter only New York listings
  { $match: { "city": "New York" } },
  // Group by the `build` field, count each group
  { 
    $group: {
      "_id": "$build", // Use the `build` value as the group identifier
      "totalListings": { $sum: 1 } // Add 1 for each document in the group
    }
  },
  // Optional: Sort results by count (descending) for readability
  { $sort: { "totalListings": -1 } }
])

Output:

{ "_id": "concrete", "totalListings": 2 }
{ "_id": "wood", "totalListings": 1 }
{ "_id": "asphalt", "totalListings": 1 }

2. Count Listings by Number of Beds (Group by beds field)

If you want to see how many listings have 1 bed, 2 beds, etc.:

db.listings.aggregate([
  { $match: { "city": "New York" } },
  { 
    $group: {
      "_id": "$beds",
      "listingCount": { $sum: 1 }
    }
  },
  // Optional: Sort by bed count (ascending)
  { $sort: { "_id": 1 } }
])

Output:

{ "_id": 1, "listingCount": 1 }
{ "_id": 2, "listingCount": 1 }
{ "_id": 3, "listingCount": 1 }
{ "_id": 4, "listingCount": 1 }

3. Optional: Format Results as a Key-Value Object

If you prefer a cleaner key-value output instead of separate documents, you can add extra stages to reshape the data:

db.listings.aggregate([
  { $match: { "city": "New York" } },
  { $group: { "_id": "$build", "count": { $sum: 1 } } },
  // Prepare data for key-value conversion
  { $project: { "k": "$_id", "v": "$count", "_id": 0 } },
  { $group: { "_id": null, "stats": { $push: "$$ROOT" } } },
  // Convert array to object
  { $replaceRoot: { newRoot: { $arrayToObject: "$stats" } } }
])

Output:

{ "concrete": 2, "wood": 1, "asphalt": 1 }

Quick Recap

  • Use $match first to filter your dataset (like targeting New York)
  • In $group, set _id: "$yourField" to group by that single field
  • $sum: 1 is the standard way to count documents per group
  • Add $sort or reshaping stages like $arrayToObject to tweak the output to your needs

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:53:44