MongoDB基于单字段输出的统计计数:进阶需求咨询
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
$matchfirst to filter your dataset (like targeting New York) - In
$group, set_id: "$yourField"to group by that single field $sum: 1is the standard way to count documents per group- Add
$sortor reshaping stages like$arrayToObjectto tweak the output to your needs
内容的提问来源于stack exchange,提问作者Aaron

