'How to groupby by _id in mongo
For VendorItem collection, I want to have my items grouped by(like SQL) in category but using group in mongo there are no accumulator for _id! Help me Thaks in advance.
param -> vendor's id
Output : [category_id1 : [ it's items ], category_id2: [it's items]]
Model
let vendorItemSchema = mongoose.Schema({
category: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref:'VendorCategory'
},
vendor : {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: Vendor
},
item: {type: String, required: true},
price: {type: Number, required: true},
inStock: {type: Boolean, required: true},
//order:{}
});
vendorItemSchema.index({category: 1});
const VendorItem = mongoose.model('VendorItem',vendorItemSchema);
Solution 1:[1]
It's the equivalent of the following SQL instruction: SELECT COUNT() FROM Table GROUP BY your_field HAVING COUNT() > N
**query = db.collection.aggregate([
{
"$group": { "_id": "$your_field", #GROUP BY your_field
"count": {"$sum":1} } #COUNT(*)
},
{ "$match": { "count": { "$gt": N } } } #HAVING COUNT(*) > N
])**
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Meherban Singh |
