Sorting mongoose按不同集合中对象id的计数排序
我有一系列的文章,比如Sorting mongoose按不同集合中对象id的计数排序,sorting,mongoose,collections,count,objectid,Sorting,Mongoose,Collections,Count,Objectid,我有一系列的文章,比如 var articleSchema = new Schema( { link: { type: String, required: true, unique: true }, title: { type: String }, description: {type: String }, source: { type: Schema.ObjectId, ref: 'sources' }, … }; 源通过objectId链接到源架
var articleSchema = new Schema(
{
link: { type: String, required: true, unique: true },
title: { type: String },
description: {type: String },
source: { type: Schema.ObjectId, ref: 'sources' },
…
};
源通过objectId链接到源架构
var sourceSchema = new Schema(
{
name: { type: String, required: true, lowercase: true },
short_handle: { type: String, required: true, lowercase: true, unique: true },
website: { type: String, required: true, lowercase: true, unique: true },
…
}
我想做的是:查询来源并根据链接到该来源的文章数量对其进行排序。这有可能吗 在为每篇文章添加源代码引用时,您需要查询
文章
模型。需要执行聚合以按分组和排序的顺序获得所需的结果
await Article
.aggregate([
{ "$group": {
"_id": '$source',
"articleCount": { "$sum": 1 }
}},
{ "$sort": { "articleCount": -1 } }
]);
此查询按排序顺序返回源及其相关文章计数的列表。在我的例子中,这里是输出
[ { _id: 5b7c7cf407d686e60a07e4e1, articleCount: 4 },
{ _id: 5b7c7cc707d686e60a07e4df, articleCount: 2 },
{ _id: 5b7c7ce407d686e60a07e4e0, articleCount: 1 } ]
在为每篇文章添加源代码引用时,需要查询
文章
模型。需要执行聚合以按分组和排序的顺序获得所需的结果
await Article
.aggregate([
{ "$group": {
"_id": '$source',
"articleCount": { "$sum": 1 }
}},
{ "$sort": { "articleCount": -1 } }
]);
此查询按排序顺序返回源及其相关文章计数的列表。在我的例子中,这里是输出
[ { _id: 5b7c7cf407d686e60a07e4e1, articleCount: 4 },
{ _id: 5b7c7cc707d686e60a07e4df, articleCount: 2 },
{ _id: 5b7c7ce407d686e60a07e4e0, articleCount: 1 } ]
听起来不错!我没有使用.Aggregate,但是,我可以在该查询中填充ID吗?@GerritHillebrecht是的,您可以这样做,但它将执行另一个查询,检查文档:在执行聚合后执行此操作。填充(结果,{path:“source”},回调);我没有得到“articleCount”计数部分,我们也得到了总数吗?听起来不错!我没有使用.Aggregate,但是,我可以在该查询中填充ID吗?@GerritHillebrecht是的,您可以这样做,但它将执行另一个查询,检查文档:在执行聚合后执行此操作。填充(结果,{path:“source”},回调);我没有得到“articleCount”计数部分,我们也得到总数了吗?