Hello all i have different document containing "category" field i have to get result from aggregation query to find number of document in each category and find result in array which sould contain {_id and num } field;
{
"_id": NumberInt(23),
"title": "WiredTiger T-shirt",
"slogan": "Unleash the tiger",
"description": "Crafted from ultra-soft combed cotton, this essential t-shirt features sporty contrast tipping and MongoDB's signature leaf.",
"stars": NumberInt(0),
"category": "Apparel",
"img_url": "/img/products/wt-shirt.jpg",
"price": 22
}
{
"_id": NumberInt(22),
"title": "Water Bottle",
"slogan": "Glass water bottle",
"description": "High quality glass bottle provides a healthier way to drink. Silicone sleeve provides a good grip, a see-through window, and protects the glass vesse [...]",
"stars": NumberInt(0),
"category": "Kitchen",
"img_url": "/img/products/water-bottle.jpg",
"price": 23
}
我有很多像这样的文件。 我使用了以下查询: -
db.collectionname.find({类别: “类别名称”},{_ ID:1})计数(); 但在这个阶段我只会得到一个类别的数据。
答案 0 :(得分:1)
您必须为此查询使用组。对于组,您必须在mongodb中使用aggreagetion。以下将做你想要的:
db.collection.aggregate([{$group: {_id: "$category", num: {$sum: 1}}}]);
mongodb文档也有一个例子: https://docs.mongodb.org/manual/reference/command/count/