mongodb聚合查询优化_mongodb聚合框架的索引优化

本文围绕Mongo 2.4.4中的match - unwind - group - sort聚合管道加速问题展开。提到match操作包含16个字段的范围查询,已用.explain()优化范围查询。探讨了是否有类似优化聚合的功能,给出了db.collection.runCommand(\aggregate\ {pipeline: YOUR_PIPELINE, explain: true})的解决方案,还讨论了聚焦索引优化的正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I have a match-unwind-group-sort aggregation pipeline in mongo 2.4.4 and I need to speed up the aggregation.

The match operation consists of range queries on 16 fields. I've used the .explain() method to optimize range queries (i.e. create compound indexes). Is there a similar function for optimizing the aggregation? I'm looking for something like:

db.col.aggregate([]).explain()

Also, am I right to focus on index optimization?

解决方案

For the first question, yes, you can explain aggregates.

db.collection.runCommand("aggregate", {pipeline: YOUR_PIPELINE, explain: true})

For the second one, the indexes you create to optimize the range queries will also apply to the $match stage of the aggregation pipeline, if they occur at the beginning of the pipeline. So you are right to focus on index optimizations.

Update 2

More about aggregate and explain: on version 2.4 it is unreliable; on 2.6+ it does not provide query execution data. https://groups.google.com/forum/#!topic/mongodb-user/2LzAkyaNqe0

Update 1

Transcript of an aggregation explain on MongoDB 2.4.5.

$ mongo so

MongoDB shell version: 2.4.5

connecting to: so

> db.q19329239.runCommand("aggregate", {pipeline: [{$group: {_id: '$user.id', hits: {$sum: 1}}}, {$match: {hits: {$gt: 10}}}], explain: true})

{

"serverPipeline" : [

{

"query" : {

},

"projection" : {

"user.id" : 1,

"_id" : 0

},

"cursor" : {

"cursor" : "BasicCursor",

"isMultiKey" : false,

"n" : 1031,

"nscannedObjects" : 1031,

"nscanned" : 1031,

"nscannedObjectsAllPlans" : 1031,

"nscannedAllPlans" : 1031,

"scanAndOrder" : false,

"indexOnly" : false,

"nYields" : 0,

"nChunkSkips" : 0,

"millis" : 0,

"indexBounds" : {

},

"allPlans" : [

{

"cursor" : "BasicCursor",

"n" : 1031,

"nscannedObjects" : 1031,

"nscanned" : 1031,

"indexBounds" : {

}

}

],

"server" : "ficrm-rafa.local:27017"

}

},

{

"$group" : {

"_id" : "$user.id",

"hits" : {

"$sum" : {

"$const" : 1

}

}

}

},

{

"$match" : {

"hits" : {

"$gt" : 10

}

}

}

],

"ok" : 1

}

Server version.

$ mongo so

MongoDB shell version: 2.4.5

connecting to: so

> db.version()

2.4.5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值