php給mongodb新增索引
阿新 • • 發佈:2021-06-11
<?php /** * mongo欄位加索引 * Created by PhpStorm. * User: Administrator * Date: 2021/6/11 * Time: 15:02 */ $mongoDB = 'deyibao';//mongo資料庫名 $mongoClient = new MongoClient();//mongo連線 $db = $mongoClient->selectDB($mongoDB);//選擇資料庫 $collectionNames = $db->getCollectionNames();//獲取所有的集合名 $rule1 = '/task_record_.*/';//正則表示式 $rule2 = '/turn_.+_record_.*/'; foreach ($collectionNames as $k=>$v){ $index = $db->$v->getIndexInfo();//獲取索引 if (preg_match_all($rule1,$v)){ foreach ($index as $key=>$val){ if (!strstr('date',$val['name'])) $collection = $db->$v->ensureIndex(['date' => 1],['background'=>true]); if (!strstr('userId',$val['name'])) $collection = $db->$v->ensureIndex(['userId' => 1],['background'=>true]); } } if (preg_match_all($rule2,$v) || strstr($v,'turn_luck_money')){ foreach ($index as $key=>$val){ if (!strstr('date',$val['name'])) $collection = $db->$v->ensureIndex(['date' => 1],['background'=>true]); if (!strstr('userId',$val['name'])) $collection = $db->$v->ensureIndex(['userId' => 1],['background'=>true]); if (!strstr('type',$val['name'])) $collection = $db->$v->ensureIndex(['type' => 1],['background'=>true]); if (!strstr('createTime',$val['name'])) $collection = $db->$v->ensureIndex(['createTime' => 1],['background'=>true]); } } if (strstr($v,'turn_user_sign') || strstr($v,'turn_message') || strstr($v,'turn_group_ranklist_log')) { foreach ($index as $key=>$val){ if (!strstr('userId',$val['name'])) $collection = $db->$v->ensureIndex(['userId' => 1],['background'=>true]); } } if (strstr($v,'turn_group_ranklist')) { foreach ($index as $key=>$val){ if (!strstr('date',$val['name'])) $collection = $db->$v->ensureIndex(['date' => 1],['background'=>true]); if (!strstr('groupId',$val['name'])) $collection = $db->$v->ensureIndex(['groupId' => 1],['background'=>true]); } } if (strstr($v,'turn_contribution')) { foreach ($index as $key=>$val){ if (!strstr('userId',$val['name'])) $collection = $db->$v->ensureIndex(['userId' => 1],['background'=>true]); if (!strstr('ctbUserId',$val['name'])) $collection = $db->$v->ensureIndex(['ctbUserId' => 1],['background'=>true]); if (!strstr('date',$val['name'])) $collection = $db->$v->ensureIndex(['date' => 1],['background'=>true]); if (!strstr('tierNum',$val['name'])) $collection = $db->$v->ensureIndex(['tierNum' => 1],['background'=>true]); } } if (strstr($v,'turn_exchange')) { foreach ($index as $key=>$val){ if (!strstr('date',$val['name'])) $collection = $db->$v->ensureIndex(['date' => 1],['background'=>true]); if (!strstr('configId',$val['name'])) $collection = $db->$v->ensureIndex(['configId' => 1],['background'=>true]); if (!strstr('userId',$val['name'])) $collection = $db->$v->ensureIndex(['userId' => 1],['background'=>true]); if (!strstr('type',$val['name'])) $collection = $db->$v->ensureIndex(['type' => 1],['background'=>true]); } } }