MongoDB查询优化

时间:2015-01-08 09:50:13

标签: javascript node.js mongodb mongoose aggregation-framework

我希望从我的用户模型中检索如下所示的几个信息:

var userSchema = new mongoose.Schema({
  email: { type: String, unique: true, lowercase: true },
  password: String,

  created_at: Date,
  updated_at: Date,

  genre : { type: String, enum: ['Teacher', 'Student', 'Guest'] },
  role : { type: String, enum: ['user', 'admin'], default: 'user' },
  active : { type: Boolean, default: false },

  profile: {
    name : { type: String, default: '' },
    headline : { type: String, default: '' },
    description : { type: String, default: '' },
    gender : { type: String, default: '' },
    ethnicity : { type: String, default: '' },
    age : { type: String, default: '' }
  },

  contacts : {
    email : { type: String, default: '' },
    phone : { type: String, default: '' },
    website : { type: String, default: '' }
  },

  location : {
    formattedAddress : { type: String, default: '' },
    country : { type: String, default: '' },
    countryCode : { type: String, default: '' },
    state : { type: String, default: '' },
    city : { type: String, default: '' },
    postcode : { type: String, default: '' },
    lat : { type: String, default: '' },
    lng : { type: String, default: '' }
  }
});

在首页,我有一个位置的过滤器,您可以在此处浏览来自国家或城市的用户。

所有字段还包含其中的用户数:

United Kingdom
  All Cities (300)
  London (150)
  Liverpool (80)
  Manchester (70)
France
  All Cities (50)
  Paris (30)
  Lille (20)
Nederland
  All Cities (10)
  Amsterdam (10)
Etc...

这在主页上,然后我还有学生和教师页面,我希望只获得有关这些国家和城市中有多少教师的信息......

我要做的是创建一个MongoDB查询,通过一个查询检索所有这些信息。

目前查询如下:

User.aggregate([
    { 
      $group: { 
        _id: { city: '$location.city', country: '$location.country', genre: '$genre' },
        count: { $sum: 1 }
      }
    },
    {
      $group: { 
        _id: '$_id.country',
        count: { $sum: '$count' },
        cities: { 
          $push: { 
            city: '$_id.city', 
            count: '$count'
          }
        },
        genres: {
          $push: {
            genre: '$_id.genre',
            count: '$count'
          }
        }
      }
    }
  ], function(err, results) {
    if (err) return next();
    res.json({ 
        res: results
    });
  });

问题是我不知道如何获得我需要的所有信息。

  • 我不知道如何获得每个国家/地区的总用户数。
  • 我有每个国家/地区的用户长度。
  • 我有每个城市的用户长度。
  • 我不知道如何获得相同但特定类型。

是否可以在Mongo中使用单个查询获取所有这些信息?

否则:

通过2,3个不同的请求向Mongo创建一些承诺:

getSomething
.then(getSomethingElse)
.then(getSomethingElseAgain)
.done

我确信每次指定数据都会更容易存储,但是:当数据库中有超过5000/10000的用户时,它对性能有好处吗?

很抱歉,我仍然在学习,我认为这些对于理解MongoDB性能/优化至关重要。

由于

1 个答案:

答案 0 :(得分:8)

您想要的是"faceted search"结果,其中包含有关当前结果集中匹配项的统计信息。随后,虽然有些产品出现了#34;要在一个响应中完成所有工作,您必须考虑到大多数通用存储引擎都需要多个操作。

使用MongoDB,您可以使用两个查询来获取结果本身,另一个查询可以获取构面信息。这样可以获得与SolrElasticSearch等专用搜索引擎产品提供的分面结果相似的结果。

但为了有效地执行此操作,您希望以有效使用的方式将其包含在文档中。您想要的一种非常有效的形式是使用一组标记化数据:

 {
     "otherData": "something",
     "facets": [
         "country:UK",
         "city:London-UK",
         "genre:Student"
     ]
 }

所以" factets"是文档中的单个字段,而不是多个位置。这使得索引和查询变得非常容易。然后,您可以有效地汇总结果并获得每个方面的总计:

User.aggregate(
    [
        { "$unwind": "$facets" },
        { "$group": {
            "_id": "$facets",
            "count": { "$sum": 1 }
        }}
    ],
    function(err,results) {

    }
);

或更理想地使用$match中的某些条件:

User.aggregate(
    [
        { "$match": { "facets": { "$in": ["genre:student"] } } },
        { "$unwind": "$facets" },
        { "$group": {
            "_id": "$facets",
            "count": { "$sum": 1 }
        }}
    ],
    function(err,results) {

    }
);

最终给出如下回复:

{ "_id": "country:FR", "count": 50 },
{ "_id": "country:UK", "count": 300 },
{ "_id": "city:London-UK", "count": 150 },
{ "_id": "genre:Student": "count": 500 }

这样的结构很容易遍历和检查像离散的国家和#34;和#34;城市"属于"国家"因为这些数据只是用一个连字符" - "。

分开

尝试在阵列中混搭文档是一个坏主意。还要遵守16MB的BSON大小限制,从而将结果混合在一起(特别是如果你试图保留文档内容)最终肯定会在响应中被超出。

对于简单的事情,然后获得"整体计数"这种查询的结果,然后只是总结特定方面类型的元素。或者只是向.count()操作发出相同的查询参数:

User.count({ "facets": { "$in": ["genre:Student"] } },function(err,count) {

});

如上所述,特别是在实施" paging"结果,然后是获得"结果计数"," Facet Counts"以及实际的"结果页面"都被委托给"分开"查询到服务器。

将每个查询并行提交到服务器,然后将结构组合到您的模板或应用程序中,看起来很像提供此类响应的搜索引擎产品之一的分面搜索结果,这没有任何问题。


结论

因此,在文档中放置一些内容以在一个位置标记构面。标记化字符串数组适用于此目的。它也适用于查询表单,例如$in$all,用于"或"或"和"小平面选择组合的条件。

不要试图混合结果或嵌套添加只是为了匹配一些感知的层次结构,而是遍历收到的结果并在令牌中使用简单的模式。

非常简单

将内容的分页查询作为单独的查询或整体计数运行。试图推送数组中的所有内容然后限制只是为了得到计数是没有意义的。这同样适用于RDBMS解决方案来做同样的事情,其中​​分页结果计数和当前页面是单独的查询操作。

MongoDB博客上有关于Faceted Search with MongoDB的更多信息,也解释了其他一些选项。还有一些文章使用mongoconnector或其他方法与外部搜索解决方案集成。

相关问题