【发布时间】:2016-01-28 11:16:05
【问题描述】:
我已经使用 createIndex 创建了索引,然后确保使用 ensureIndex
db.getCollection('artists').createIndex( { featured : NumberInt(-1), physicalCount : NumberInt(-1),digitalCount : NumberInt(-1),createdAt: NumberInt(-1) } )
db.getCollection('artists').ensureIndex( { featured : NumberInt(-1), physicalCount : NumberInt(-1),digitalCount : NumberInt(-1),createdAt: NumberInt(-1) } )
创建索引:
"8" : {
"v" : 1,
"key" : {
"featured" : -1,
"physicalCount" : -1,
"digitalCount" : -1,
"createdAt" : -1
},
"name" : "featured_-1_physicalCount_-1_digitalCount_-1_createdAt_-1",
"ns" : "global-rockstar.artists"
}
现在我想在聚合查询中使用这个索引。我知道当我们在聚合中使用 $project 或 $group 属性时索引不起作用。我想重新设计这个查询,以便它可以使用索引但无法创建一个
db.getCollection('artists').aggregate([{
$match: query <- initially it is {}
}, {
$project: {
_id: 1,
name: 1,
genres_music: 1,
slug: 1,
country: 1,
featured: 1,
picture: 1,
fans: 1,
fans_a: 1,
credits: 1,
totalPlays: 1,
createdAt: 1,
fanCount: 1,
physicalCount: 1,
digitalCount: 1,
matches: {
$add: [{
$cond: [{
$or: [{
$eq: ['$featured', true]
}, {
$eq: ['$featured', 'on']
}]
},
3, 0
]
}, {
$size: {
$setIntersection: ['$genres_music', usergenres]
}
}]
}
}
}, {
$sort: {
matches: -1,
physicalCount : -1,
digitalCount : -1,
createdAt: -1
}
}, {
$skip: pageSize * page <---- pageSize- 15 , page= 0
}, {
$limit: parseFloat(pageSize)
}])
当我像
这样触发查询时db.getCollection('artists').find({}).sort({
//"featured" : -1,
"physicalCount" : -1,
"digitalCount" : -1,
"createdAt" : -1
})
这是出乎意料的结果
如果有人知道如何使用带有索引的聚合查询,请帮帮我
【问题讨论】:
标签: node.js mongodb mongoose aggregation-framework