如何在 mongo 中按 _id 分组
How to groupby by _id in mongo
对于 VendorItem 集合,我想让我的项目在类别中按(如 SQL)分组,但在 mongo 中使用组,没有 _id 的累加器!提前帮帮我Thaks。
参数 -> 供应商的 ID
输出: [category_id1 :[这是项目],category_id2:[是项目]]
型号
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);
它等同于以下 SQL 指令:
SELECT 从 Table 计数()
分组 your_field
计数()> N
**query = db.collection.aggregate([
{
"$group": { "_id": "$your_field", #GROUP BY your_field
"count": {"$sum":1} } #COUNT(*)
},
{ "$match": { "count": { "$gt": N } } } #HAVING COUNT(*) > N
])**
查询
- 可能与分组
_id
你的意思是收集所有文档信息所以你可能需要 $$ROOT
- 下面有3个蓄电池,只留你需要的
- 合计数量,收集items(strings),收集根文件
*如果这不是您需要的,如果您可以在 json 中提供样本数据,并且预期输出
aggregate(
[{"$group":
{"_id":"$category",
"count":{"$sum":1},
"items":{"$push":"$item"},
"docs":{"$push":"$$ROOT"}}}])
对于 VendorItem 集合,我想让我的项目在类别中按(如 SQL)分组,但在 mongo 中使用组,没有 _id 的累加器!提前帮帮我Thaks。
参数 -> 供应商的 ID
输出: [category_id1 :[这是项目],category_id2:[是项目]]
型号
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);
它等同于以下 SQL 指令: SELECT 从 Table 计数() 分组 your_field 计数()> N
**query = db.collection.aggregate([
{
"$group": { "_id": "$your_field", #GROUP BY your_field
"count": {"$sum":1} } #COUNT(*)
},
{ "$match": { "count": { "$gt": N } } } #HAVING COUNT(*) > N
])**
查询
- 可能与分组
_id
你的意思是收集所有文档信息所以你可能需要$$ROOT
- 下面有3个蓄电池,只留你需要的
- 合计数量,收集items(strings),收集根文件
*如果这不是您需要的,如果您可以在 json 中提供样本数据,并且预期输出
aggregate(
[{"$group":
{"_id":"$category",
"count":{"$sum":1},
"items":{"$push":"$item"},
"docs":{"$push":"$$ROOT"}}}])