查询部分:
- mongo客户端的请求
- mongod配置服务器端对数据库的加载
- mongod query中cursor操作
- mongod对于document的匹配
mongo端的请求:
首先进入mongo的查询请求部分:将请求分装成一个Message结构,然后将其发送到服务端,等待服务端的相应数据,取得数据最后显示结果.
下面来看具体流程分析:
当我们点击db.coll.find({x:1})时,首先来到了mongo/shell/dbshell.cpp
if ( ! wascmd ) {
try {
if ( scope->exec( code.c_str() , "(shell)" , false , true , false ) )//执行相应的javascript代码
scope->exec( "shellPrintHelper( __lastres__ );" , "(shell2)" , true , true , false );
}
catch ( std::exception& e ) {
cout << "error:" << e.what() << endl;
}
}
下面进入javascript代码,其在mongo/shell/collection.js.
//这里因为我们只设置了query,所以其它选项都是空的,
//this.getQueryOptions()目前只有一个SlaveOK的option,在replset模式下是不能查询secondary服务器的,需要调用rs.SlaveOK()之后才能对secondary进行查询,其执行SlaveOK后每次查询时都会添加一个QueryOption.
DBCollection.prototype.find = function (query, fields, limit, skip, batchSize, options) {
return new DBQuery( this._mongo , this._db , this ,
this._fullName , this._massageObject( query ) , fields , limit , skip , batchSize , options || this.getQueryOptions() );
}
那么我们继续前进来到DBClientConnection::query函数,该函数只是简单调用了DBClientBase::query函数.
auto_ptr<DBClientCursor> DBClientBase::query(const string &ns, Query query, int nToReturn,
int nToSkip, const BSONObj *fieldsToReturn, int queryOptions , int batchSize ) {
auto_ptr<DBClientCursor> c( new DBClientCursor( this,//根据传入的参数创建一个DBClientCursor对象
ns, query.obj, nToReturn, nToSkip,
fieldsToR