在Mongoose中获取收集计数的表现

时间:2018-01-12 06:30:37

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

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

所以我对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
}

Blog Schema:架构中没有totalComments 字段。

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

评论架构:

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

此处博客详情&评论分别存储在博客和评论集合中。

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

现在我的问题是:

1如何在mongoose中加入两个集合?

2根据MongoDB db.collection.count()db.collection.find().count()相同。那么它会扫描所有文件吗?因此,最好使用db.collection.find()并将其存储在哪里,以便我可以使用它们?

如何提高性能?

1 个答案:

答案 0 :(得分:1)

核对lookup汇总

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