對于 VendorItem 集合,我想讓我的專案按類別(如 SQL)分組,但在 mongo 中使用組,_id 沒有累加器!提前幫我謝謝。
引數 -> 供應商的 id
輸出: [category_id1:[it's items],category_id2:[it's items]]
模型
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);
uj5u.com熱心網友回復:
詢問
- 可能與 group by
_id你的意思是收集所有檔案資訊,所以你可能需要$$ROOT - 波紋管有 3 個蓄能器,只保留你需要的
- sum 數量,收集專案(字串),收集根檔案
*如果這不是您需要的,如果您可以在 json 中提供示例資料,以及預期的輸出
aggregate(
[{"$group":
{"_id":"$category",
"count":{"$sum":1},
"items":{"$push":"$item"},
"docs":{"$push":"$$ROOT"}}}])
uj5u.com熱心網友回復:
它等效于以下 SQL 指令: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
])**
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/437004.html
