如何使用索引优化MongoDB搜索?

时间:2016-10-06 10:49:41

标签: mongodb indexing aggregation-framework

这些文档在我的MongoDB集合中:

{
  "_id" : ObjectId("57f5e1b5c7739d9805edfe85"),
  "date" : ISODate("2016-10-01T00:00:00.000Z"),
  "query" : "test1",
  "page" : "page1/runway/ready-to-wear/ss17/2016/10/christian-dior/",
  "clicks" : 17.0,
  "impressions" : 161.0,
  "ctr" : 0.10559006211180125,
  "position" : 8.503105590062113
}
{
  "_id" : ObjectId("57f5e1b5c7739d9805edfe86"),
  "date" : ISODate("2016-10-01T00:00:00.000Z"),
  "query" : "test1",
  "page" : "page2/runway/ready-to-wear/ss17/2016/10/christian-dior/",
  "clicks" : 17.0,
  "impressions" : 161.0,
  "ctr" : 0.10559006211180125,
  "position" : 8.503105590062113
}
{
  "_id" : ObjectId("57f5e1b5c7739d9805edfe87"),
  "date" : ISODate("2016-10-01T00:00:00.000Z"),
  "query" : "test2",
  "page" : "page3/runway/ready-to-wear/ss17/2016/10/christian-dior/",
  "clicks" : 17.0,
  "impressions" : 161.0,
  "ctr" : 0.10559006211180125,
  "position" : 8.503105590062113
}

我需要过滤并获取一些这样的文档:

{
  "_id" : ObjectId("57f5e1b5c7739d9805edfe85"),
  "date" : ISODate("2016-10-01T00:00:00.000Z"),
  "query" : "test1",
  "page" : "page1/runway/ready-to-wear/ss17/2016/10/christian-dior/",
  "clicks" : 17.0,
  "impressions" : 161.0,
  "ctr" : 0.10559006211180125,
  "position" : 8.503105590062113
}
{
  "_id" : ObjectId("57f5e1b5c7739d9805edfe86"),
  "date" : ISODate("2016-10-01T00:00:00.000Z"),
  "query" : "test1",
  "page" : "page2/runway/ready-to-wear/ss17/2016/10/christian-dior/",
  "clicks" : 17.0,
  "impressions" : 161.0,
  "ctr" : 0.10559006211180125,
  "position" : 8.503105590062113
}

我使用查询字段创建了一个索引,并使用db.query方法运行aggregate(),如下所示:

{ 
     "aggregate" : "Mycollection Name" ,
     "pipeline" : [ 
         { "$match" : { "$text" : { "$search" : "\"test1\""}}},
         { "$match" : { "date" : { "$gte" : { "$date" : "2016-10-  01T00:00:00.000Z"} ,"$lte" : { "$date" : "2016-10-01T00:00:00.000Z"}}}},
         { "$group" : { "_id" : "$page" , "clicks" : { "$sum" : "$clicks"} ,  "impressions" : { "$sum" : "$impressions"} , "ctr" : { "$avg" : "$ctr"} ,  "position" : { "$avg" : "$position"}}} , 
         { "$sort" : { "clicks" : -1}}
      ]
}

此查询正在运行,但它不会完全返回搜索。

如何优化此查询?

0 个答案:

没有答案