Mongo queries count very slowly.

  mongodb, question

I use mongodb3.4. Currently, there is a query that needs paging. Paging needs to return the total number and pages.
But that’s the problem. Paging queries are relatively fast, but counting is extremely slow.

The count statement is as follows:

db.message.find(
 {
 "field_1":"ajian",
 "field_2":{ "$exists": true },
 "field_3":{ "$exists": true },
 "field_4":{ "$exists": true },
 "field_5":{"$regex":value1},
 "field_6":{"$regex":value2}
 }
 ).count()

It takes 2.5 seconds to return the result!
I explain the info result as follows:

{
 "queryPlanner" : {
 "plannerVersion" : 1,
 "namespace" : "engine.message",
 "indexFilterSet" : false,
 "parsedQuery" : {
 "$and" : [
 {
 "field_1" : {
 "$eq" : "ajian"
 }
 },
 {
 "field_2" : {
 "$regex" : ""
 }
 },
 {
 "field_3" : {
 "$regex": "Not Processed"
 }
 },
 {
 "field_4" : {
 "$exists" : true
 }
 },
 {
 "field_5" : {
 "$exists" : true
 }
 },
 {
 "field_6" : {
 "$exists" : true
 }
 }
 ]
 },
 "winningPlan" : {
 "stage" : "COLLSCAN",
 "filter" : {
 "$and" : [
 {
 "field_1" : {
 "$eq" : "ajian"
 }
 },
 {
 "field_2" : {
 "$regex" : ""
 }
 },
 {
 "field_3" : {
 "$regex": "Not Processed"
 }
 },
 {
 "field_4" : {
 "$exists" : true
 }
 },
 {
 "field_5" : {
 "$exists" : true
 }
 },
 {
 "field_6" : {
 "$exists" : true
 }
 }
 ]
 },
 "direction" : "forward"
 },
 "rejectedPlans" : []
 },
 "executionStats" : {
 "executionSuccess" : true,
 "nReturned" : 1537253,
 "executionTimeMillis" : 2536,
 "totalKeysExamined" : 0,
 "totalDocsExamined" : 1610191,
 "executionStages" : {
 "stage" : "COLLSCAN",
 "filter" : {
 "$and" : [
 {
 "field_1" : {
 "$eq" : "ajian"
 }
 },
 {
 "field_2" : {
 "$regex" : ""
 }
 },
 {
 "field_3" : {
 "$regex": "Not Processed"
 }
 },
 {
 "field_4" : {
 "$exists" : true
 }
 },
 {
 "field_5" : {
 "$exists" : true
 }
 },
 {
 "field_6" : {
 "$exists" : true
 }
 }
 ]
 },
 "nReturned" : 1537253,
 "executionTimeMillisEstimate" : 2417,
 "works" : 1610193,
 "advanced" : 1537253,
 "needTime" : 72939,
 "needYield" : 0,
 "saveState" : 12588,
 "restoreState" : 12588,
 "isEOF" : 1,
 "invalidates" : 0,
 "direction" : "forward",
 "docsExamined" : 1610191
 },
 "allPlansExecution" : []
 },
 "serverInfo" : {
 "host" : "secret",
 "port" : 27017,
 "version" : "3.4.10",
 "gitVersion" : "2234234232325323343"
 },
 "ok" : 1.0
 }

Why is mongo’s count so slow? How do great gods solve this problem when they do paging? How can I solve this problem?

Simply put, queries that cannot hit any index require a full table scan, which is of course very slow. You need to add an appropriate index.