我想验证我正在创建的mongoose查询正在使用我的索引。有没有办法可以查看为mongodb生成的最终查询,以便我可以在查询上运行.explain()?
我猜猜它生成的查询是什么,但只是想验证。
e.g。
var query = Post.find()
.regex('lowerCaseTitle', searchRegEx)
.$gte('status',0)
.$lt('start', now)
.$gt('end',now)
.sort('total', -1)
.limit(50);
答案 0 :(得分:47)
您可以使用mongoose上的调试选项获取执行查询:
mongoose.set('debug', true);
或
mongoose.set('debug', function (collectionName, method, query, doc, options) {
//
});
答案 1 :(得分:1)
另一个选择:
model
.find()
.{{...}} // any thing else
.setOptions({explain: 'executionStats'})
.exec((e, explainObj)=>{
...
})
答案 2 :(得分:0)
您也可以直接使用Query.prototype.explain()(作为Mongoose 5.2.13)
var query = Post.find()
.regex('lowerCaseTitle', searchRegEx)
.$gte('status',0)
.$lt('start', now)
.$gt('end',now)
.sort('total', -1)
.limit(50);
query.explain().then(console.log);
答案 3 :(得分:-2)
一种方法是使用mongodb分析器并将其设置为记录所有操作:
http://www.mongodb.org/display/DOCS/Database+Profiler
我不确定是否有更简单的方法通过猫鼬本身来做到这一点,但这样会很好。
更新:除了Dan在其他答案的评论中所说的,你应该打开探查器以获得你想要的东西,并将其关闭。将其留作“记录所有操作”绝对是减慢系统速度的好方法。将其限制在开发环境中也是一个好主意。
答案 4 :(得分:-2)
最简单的方法可能是在MongoDB shell中复制该查询。类似的东西:
> var now = new Date();
> db.post.find({lowerCaseTitle: /your_regex_here/, status: {$gte: 0}, start: {$lt: now}, end: {$gt: now}}).sort({total: -1}).limit(50)
这应该返回与mongoose.js中的查询相同的结果。然后,您可以添加.explain()
以查看MongoDB使用的执行计划:
> db.post.find({lowerCaseTitle: /your_regex_here/, status: {$gte: 0}, start: {$lt: now}, end: {$gt: now}}).sort({total: -1}).limit(50).explain()