【问题标题】:Performance of getting count of collection in Mongoose在 Mongoose 中获取集合计数的性能
【发布时间】:2018-06-21 14:10:43
【问题描述】:

我正在开发一个 api,我将在其中返回用户 A 博客文章的详细信息。

所以我从 api 得到的回应如下:

{
BlogDetail : {
   id : 1,
   title : 'My blog',
   ....
   totalComments : 123, //Always present

   //Add comments based on user parameter getComment in api -- If true append else dont 

   comments : [{
      user : 'Steve Smith',
      comment ; 'Virat learn from me how to bat in test cricket'
   },
   ....]


},
..... //Other Fields
}

博客架构:架构中不会有 totalComments 字段。

 {
   _id : 1,
   title: 'xyz',
   ....
 }

评论架构:

{
   _id : 1,
   blog_id: 1,
   user : 'abc',
   comment: 'xyz'
   ....
 }

这里的博客详细信息和评论分别存储在博客和评论集合中。

根据用户参数,我将附加评论作为回应。但总是会返回该帖子上的 cmets 总数。

现在我的问题是:

1 如何在mongoose加入两个收藏?

2 根据 MongoDB,db.collection.count()db.collection.find().count() 是相等的。所以它会扫描所有文件?所以最好使用db.collection.find() 并将其存储在某个地方以便我可以使用它们?

如何提高性能?

【问题讨论】:

    标签: mongodb performance mongoose mongodb-query mongoose-schema


    【解决方案1】:

    综合检查lookup

    ```
    BlogDetail.aggregate([{
        $lookup: {
            from: "Comments",
            localField: "_id",
            foreignField: "Comments",
            as: "Comments"
        }
    }]).exec(function(err, students) {
        // do whatever you want
    });
    ```
    

    【讨论】:

    • 尝试在mongoose中填充,但保存时需要添加cmets对blogdetails的引用。
    猜你喜欢
    • 1970-01-01
    • 2018-08-21
    • 2016-06-20
    • 1970-01-01
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    • 1970-01-01
    相关资源
    最近更新 更多