可以在文件本身中指定开始时间和结束时间。下面是一个例子:
  
  var start_time = new Date().valueOf();
db.telephone.find({'brand' : 'Apple'});
db.telephone.find({'brand' : 'Samsung'});
var end_time = new Date().valueOf();
print(end_time-start_time);
  
   
    我们如何精确地测量执行时间?
   
  
  
   要分析查询,可以使用
   
    explain()
   
   . 它返回查询的完整统计信息。下面是一个例子:
  
  db.telephone.find({'brand' : 'Apple'}).explain("executionStats")
  
   
    输出:
   
  
  {
    "queryPlanner" : {
        "plannerVersion" : 1,
        "namespace" : "check.telephone",
        "indexFilterSet" : false,
        "parsedQuery" : {
            "brand" : {
                "$eq" : "Apple"
            }
        },
        "winningPlan" : {
            "stage" : "COLLSCAN",
            "filter" : {
                "brand" : {
                    "$eq" : "Apple"
                }
            },
            "direction" : "forward"
        },
        "rejectedPlans" : [ ]
    },
    "executionStats" : {
        "executionSuccess" : true,
        "nReturned" : 1,
        "executionTimeMillis" : 35,
        "totalKeysExamined" : 0,
        "totalDocsExamined" : 1,
        "executionStages" : {
            "stage" : "COLLSCAN",
            "filter" : {
                "brand" : {
                    "$eq" : "Apple"
                }
            },
            "nReturned" : 1,
            "executionTimeMillisEstimate" : 0,
            "works" : 3,
            "advanced" : 1,
            "needTime" : 1,
            "needYield" : 0,
            "saveState" : 0,
            "restoreState" : 0,
            "isEOF" : 1,
            "invalidates" : 0,
            "direction" : "forward",
            "docsExamined" : 1
        }
    },
    "serverInfo" : {
        "host" : "theMechanic",
        "port" : 27017,
        "version" : "4.0.11",
        "gitVersion" : "417d1a712e9f040d54beca8e4943edce218e9a8c"
    },
    "ok" : 1
}
  
   
    注:
   
   这个
   
    executionStats.executionTimeMillis
   
   保留实际查询执行时间。