user2410781
user2410781

Reputation:

mongoose sort by count of object id in diffrerent collection

I have a Collection of Articles, like

var articleSchema = new Schema(
{
    link: { type: String, required: true, unique: true  },
    title: { type: String },
    description: {type: String },
    source: { type: Schema.ObjectId, ref: 'sources' },
    … 
};

The Source links via objectId to the Source schema.

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 },
    …
}

What i want to do: querying the sources and sorting them by the amount of articles linked to that sources. Is that somehow possible?

Upvotes: 0

Views: 1205

Answers (1)

Shivam Pandey
Shivam Pandey

Reputation: 3936

As you are adding source reference to each article, you will need to query on Article model. Need to perform aggregation to get the required results in grouped and sorted order.

await Article
    .aggregate([

        { "$group": { 
            "_id": '$source', 
            "articleCount": { "$sum": 1 }
        }},

        { "$sort": { "articleCount": -1 } }
]);

This query returns a list of source and their related articles count in sorted order. In my case, here is the output.

[ { _id: 5b7c7cf407d686e60a07e4e1, articleCount: 4 },
  { _id: 5b7c7cc707d686e60a07e4df, articleCount: 2 },
  { _id: 5b7c7ce407d686e60a07e4e0, articleCount: 1 } ]

Upvotes: 5

Related Questions