gpt4 book ai didi

node.js - 如何使用聚合索引

转载 作者:太空宇宙 更新时间:2023-11-04 00:48:58 24 4
gpt4 key购买 nike

我已经使用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
})

这给出了意想不到的结果

如果有人知道如何使用带有此查询索引的聚合查询,请帮助我

最佳答案

根据 MongoDB 文档:

The $match and $sort pipeline operators can take advantage of an index when they occur at the beginning of the pipeline.

因此,如果可以的话,您应该将 $sort 阶段放在 $project 和 $group 阶段之前。

Placing a $match pipeline stage followed by a $sort stage at the start of the pipeline is logically equivalent to a single query with a sort and can use an index. When possible, place $match operators at the beginning of the pipeline.

此外,最好尽早放置 $skip 和 $limit 阶段。

Early Filtering If your aggregation operation requires only a subset of the data in a collection, use the $match, $limit, and $skip stages to restrict the documents that enter at the beginning of the pipeline. When placed at the beginning of a pipeline, $match operations use suitable indexes to scan only the matching documents in a collection.

最后,

For a compound index, MongoDB can use the index to support queries on the index prefixes.

关于node.js - 如何使用聚合索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33395168/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com