我如何基于特定字段在MongoDB中获取计数

huangapple go评论62阅读模式
英文:

How do I get count in MongoDB based on specific fields

问题

我有类似这样的文档在我的MongoDB Listings集合中。

listingID: 'abcd',
listingData: {
    category: 'residential'
},
listingID: 'xyz',
listingData: {
    category: 'residential'
},
listingID: 'efgh',
listingData: {
    category: 'office'
}

我正在尝试获取所有列表的总数以及按类别计数。

我可以使用聚合查询获取所有列表的总数。但是我不确定如何获得像这样的输出 residentialCount: 2, officeCount: 1, ListingsCount: 3

这是我的聚合查询

{
    $match: {
        listingID,
    },
},
{
    $group: {
        _id: 1,
        ListingsCount: { $sum: 1 },
    },
}
英文:

I have documents like this in my MongoDB Listings collection.

listingID: 'abcd',
listingData: {
    category: 'resedetial'
},
listingID: 'xyz',
listingData: {
    category: 'resedetial'
},
listingID: 'efgh',
listingData: {
    category: 'office'
}

I am trying to get total count of all listings and count according to category.

I can get total count of listings with aggregation query. But I am not sure how to get output like this resedentialCount: 2, officeCount: 1 , ListingsCount: 3

This is my aggregation query

{
    $match: {
        listingID,
    },
},
{
    $group: {
        _id: 1,
        ListingsCount: { $sum: 1 },
    },
}

答案1

得分: 1

尝试这个:

let listingAggregationCursor = db.collection.aggregate([
    {$group: {_id:"$listingData.category", ListingsCount:{$sum:1} }}
])

let listingAggregation = await listingAggregationCursor.toArray();

这将给您一个包含每个列表类别以及它们出现次数的对象数组。

要获取总的列表计数,请将数组中所有计数字段相加。您可以这样做:

let listingsCount = 0;
for (listingCategory of listingAggregation) {
    listingsCount += listingCategory.ListingsCount;
}

到这一步,您应该已经获得所需的数据。现在只需要根据您的需求提取和格式化它。

希望这有所帮助!

英文:

Try this:

let listingAggregationCursor = db.collection.aggregate([
    {$group: {_id:"$listingData.category",ListingsCount:{$sum:1} }}
])

let listingAggregation=await listingAggregationCursor.toArray();

(I got this query from https://www.statology.org/mongodb-group-by-count)

This will give you an array of objects with each listing category as well as how many times they occur.

For getting the total listingsCount, sum up all of the count fields from the array of objects. You can do that like this:

let listingsCount=0;
for(listingCategory of listingAggregation) {
    listingsCount+=listingCategory.count;
}

You should have the data you need at this point. Now it's just a matter of extracting and formatting it as you see fit.

Hope this helps!

huangapple
  • 本文由 发表于 2023年1月6日 17:55:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75029394.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定