在聚合管道中使用索引的问题

时间:2018-09-05 13:21:40

标签: mongodb mongodb-query aggregation-framework

我有这样的查询

db.UserPosts.aggregate([
{ "$match" : { "Posts.DateTime" : { "$gte" : ISODate("2018-09-04T11:50:58Z"), "$lte" : ISODate("2018-09-05T11:50:58Z") } } }, 
{ "$match" : { "UserId" : { "$in" : [NUUID("aaaaaaaa-cccc-dddd-dddd-5369b183cccc"), NUUID("vvvvvvvv-bbbb-ffff-cccc-e0af0c8acccc")] } } },     
    { "$project" : { "_id" : 0, "UserId" : 1, "Posts" : 1 } }, 
    { "$unwind" : "$Posts" },     
    { "$unwind" : "$Posts.Comments" },     
    { "$sort" : {"Posts.DateTime" : -1} },     
    { "$skip" : 0 }, { "$limit" : 20 },
    { "$project" : { "_id" : 0, "UserId" : 1, "DateTime" : "$Posts.DateTime", "Title" : "$Posts.Title", "Type" : "$Posts.Comments.Type", "Comment" : "$Posts.Comments.Description" } },
    ],{allowDiskUse:true})

我有一个复合索引

{
    "Posts.DateTime" : -1,
    "UserId" : 1
}

帖子和评论是对象数组。 我尝试了不同类型的索引,但是问题是它没有在$ sort阶段使用我的索引。我更改了$ sort阶段的位置,但未成功。似乎它在$ match中工作,但未设置为$ sort。我什至在这些字段上尝试了2个简单索引,并组合了2个简单索引和一个复合索引,但是它们都不起作用。 我还在MongoDB网站上阅读了有关文件

  • 化合物指数
  • 使用索引对查询结果进行排序
  • 索引交集
  • 聚合管道优化

有人可以帮我找到解决方案吗?

1 个答案:

答案 0 :(得分:0)

我通过更改数据模型并将DateTime移动到更高级别的数据来解决了这个问题。