Sameer Thite
Sameer Thite

Reputation: 43

Mongodb mongoose query get count of documents by reference

I have 2 collections in mongodb. articles and tags. In articles, there can be multiple tags. Following is the article schema:

const mongoose = require('mongoose');
const articleSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true,
        trim: true
    },
    tags: [{
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'Tag'
    }]
}, {
    timestamps: true
});
const Article = mongoose.model('Article', articleSchema);
module.exports = Article;

Following is the tag schema:

const mongoose = require('mongoose');
const tagSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true,
        trim: true,
        unique: true
    }
}, {
    timestamps: true
});
const Tag = mongoose.model('Tag', tagSchema);
module.exports = Tag;

From these collections I wanted to show a simple column chart which shows how many articles are there against a tag. I am trying to get data in format like this:

const data = [
  { title: 'Javascript', count: 20 },
  { title: 'ReactJs', count: 12 },
  { title: 'NodeJs', count: 5 }
];

I have tried aggregate, $lookup but not able to find solution. Also tried this answer

Following I have tried but its not giving desired output.

const result = await Tag.aggregate([
        {
            $lookup:
            {
                from: "articles",
                localField: "_id",
                foreignField: "tags",
                as: "articles"
            }
        }
    ])

It gives output like this, it returns articles array against tag but I need count of articles only.

[{
    "_id": "5f6f39c64250352ec80b0e10",
    "title": "ReactJS",
    articles: [{ ... }, { ... }]
},{
    "_id": "5f6f40325716952d08a6813c",
    "title": "Javascript",
    articles: [{ ... }, { ... },{ ... }, { ... }]
}]

If anyone knows solution, please let me know. Thank you.

Upvotes: 4

Views: 591

Answers (1)

turivishal
turivishal

Reputation: 36104

  • $lookup with articles collection
  • $project to show required fields and get total size of articles array using $size
const result = await Tag.aggregate([
  {
    $lookup: {
      from: "articles",
      localField: "_id",
      foreignField: "tags",
      as: "articles"
    }
  },
  {
    $project: {
      _id: 0,
      title: 1,
      count: { $size: "$articles" }
    }
  }
])

Playground

Upvotes: 3

Related Questions