MongoDB猫鼬查询通过引用获取文档计数

萨米尔·蒂特(Sameer Thite)

我在mongodb中有2个收藏集。文章和标签。在文章中,可以有多个标签。以下是文章架构:

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;

以下是标记架构:

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;

从这些集合中,我想显示一个简单的柱形图,该图显示在一个标签上有多少篇文章。我正在尝试以这种格式获取数据:

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

我试过聚合,$查找,但找不到解决方案。还尝试了这个答案

以下我尝试过,但没有给出期望的输出。

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

它给出这样的输出,它返回针对标签的articles数组,但是我只需要计数文章。

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

如果有人知道解决方案,请告诉我。谢谢。

土生的
  • $lookuparticles收藏
  • $project显示必填字段并articles使用$size
const result = await Tag.aggregate([
  {
    $lookup: {
      from: "articles",
      localField: "_id",
      foreignField: "tags",
      as: "articles"
    }
  },
  {
    $project: {
      _id: 0,
      title: 1,
      count: { $size: "$articles" }
    }
  }
])

操场

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章