我的案例与(MongoDB aggregate count is too much slow)案例非常相似,我有40.000个文档,并且此汇总需要8秒才能显示总共10个文档(限制)的总数(40.000)。>
P.S。如果我运行customer.find()。count(),它将在不到1秒的时间内返回40.000的计数
这是我的查询
aggregate([
{
"$match": {}
},
{
"$lookup": {
"from": "core.entities",
"localField": "entityId",
"foreignField": "_id",
"as": "entity"
}
},
{
"$unwind": "$entity"
},
{
"$project": {
"entity._id": 0
}
},
{
"$replaceRoot": {
"newRoot": {
"$mergeObjects": [
"$entity",
"$$ROOT"
]
}
}
},
{
"$project": {
"entity": 0
}
},
{
$facet: {
paginatedResults: [
{
$skip: 0
},
{
$limit: 10
}
],
totalCount: [
{
$count: 'count'
}
]
}
}])
这是我的客户集合索引:
[{
"v": 2,
"key": {
"_id": 1
},
"name": "_id_",
"ns": "applekkus-gmp.core.customers"
},
{
"v": 2,
"key": {
"name": 1
},
"name": "name_1",
"ns": "applekkus-gmp.core.customers"
}]
...这是我的实体集合索引:
[{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "applekkus-gmp.core.entities"
}]
...这是我的汇总explain():
"stages": [
{
"$cursor": {
"query": {
},
"queryPlanner": {
"plannerVersion": 1,
"namespace": "applekkus-gmp.core.customers",
"indexFilterSet": false,
"parsedQuery": {
},
"winningPlan": {
"stage": "COLLSCAN",
"direction": "forward"
},
"rejectedPlans": []
}
}
},
{
"$lookup": {
"from": "core.entities",
"as": "entity",
"localField": "entityId",
"foreignField": "_id",
"unwinding": {
"preserveNullAndEmptyArrays": false
}
}
},
{
"$project": {
"entity": {
"_id": false
}
}
},
{
"$replaceRoot": {
"newRoot": {
"$mergeObjects": [
"$entity",
"$$ROOT"
]
}
}
},
{
"$project": {
"entity": false
}
},
{
"$facet": {
"paginatedResults": [
{
"$limit": NumberLong(10)
}
],
"totalCount": [
{
"$group": {
"_id": {
"$const": null
},
"count": {
"$sum": {
"$const": 1
}
}
}
},
{
"$project": {
"_id": false,
"count": true
}
}
]
}
}
],"ok": 1