php mongo model
class LibMongo {
private static $_instance = null;
/**
* @var MongoDB\Driver\Manager
*/
private $_manager = null;
/**
* @var MongoDB\Driver\WriteConcern
*/
private $_write_concern = null;
public static function getInstance() {
if(self::$_instance === null) {
self::$_instance = new LibMongo();
}
return self::$_instance;
}
public function getManager() {
if($this->_manager === null) {
$this->_manager = new MongoDB\Driver\Manager('mongodb://127.0.0.1:27017',array('username'=>'root','password'=>'root'));
}
return $this->_manager;
}
public function getWriteConcern() {
if($this->_write_concern === null) {
$this->_write_concern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
}
return $this->_write_concern;
}
public function getNewObjectID() {
$object_id = new MongoDB\BSON\ObjectID;
return $object_id;
}
/**
* @return \MongoDB\Driver\BulkWrite
*/
public function getNewBulkWrite() {
return new MongoDB\Driver\BulkWrite;
}
public function getQuery($filter = [], $options = ['projection' => ['_id' => 0], 'sort' => ['x' => -1]]) {
return new MongoDB\Driver\Query($filter, $options);
}
select
$where = [
'driver_phone' => $phone_number
];
$query = LibMongo::getInstance()->getQuery($where, ['projection' => ['_id' => 0]]);
$manager = LibMongo::getInstance()->getManager();
$cursor = $manager->executeQuery('collection_name', $query);
$cursor = $cursor->toArray();
insert
$bulk = LibMongo::getInstance()->getNewBulkWrite();
$manager = LibMongo::getInstance()->getManager();
$options = [
'upsert' => true
];
foreach($data as $index => $value){
$where = [
'plate_number' => $value['REGNO']
];
$document = [
'$set' => [
'vin' => $value['VINNO']
],
'$addToSet' => [
'breakdown' => [
'file_id' => $value['FILE_ID'],
'case_number' => $value['SECID'],
'lev_code' => $value['LEV_CODE'],
'lev_name_chi' => $value['LEV_NAME'],
'caller_name' => $value['CALLER'],
'caller_phone' => $value['CALLERTEL'],
'crdate' => new MongoDB\BSON\UTCDateTime(strtotime($value['CRDATE']) * 1000)
]
]
];
$bulk->update($where, $document, $options);
if($index % 20 == 0){
$manager->executeBulkWrite('collections_name', $bulk, LibMongo::getInstance()->getWriteConcern());
$bulk = LibMongo::getInstance()->getNewBulkWrite();
}
}
if($bulk->count() > 0){
$manager->executeBulkWrite('collections_name', $bulk, LibMongo::getInstance()->getWriteConcern());
}
auth登陆
mongo
>use admin
>db.auth('root','123456')
show dbs
use db
show tables | show collections
--
db.dropDatabase() # 删除当前正在使用的数据库
删除集合 db.collection_name.drop()
--
创建数据库和集合
# 当你使用一个不存在的mongo数据库时,就自动创建了一个mongo数据库
# 同理当你往一个空集合里面插入了一条数据之后就自动创建了一个集合
查看当前数据库状态
db.stats()
查看当前数据库版本
db.version()
备份数据库
导出
mongodump --host IP --port 端口 -u 用户名 -p 密码 -d 数据库 -o 文件路径
导入
mongorestore --host --port -d 文件路径
db.collection_name.find() # 查所有满足条件数据
db.collection_name.findOne() # 查满足条件的一条数据
db.collection_name.count() # 统计集合下面有多少数量的数据
删除用户db.removeUser("userName")
;
db.help():显示数据库操作命令
db.foo.help():显示集合操作命令
查看当前用户
> show users
{
"_id" : "admin.root",
"user" : "root",
"db" : "admin",
"roles" : [
{
"role" : "readWriteAnyDatabase",
"db" : "admin"
},
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
},
{
"role" : "dbAdminAnyDatabase",
"db" : "admin"
},
{
"role" : "clusterAdmin",
"db" : "admin"
}
]
}
> show dbs; #显示数据库列表
admin 0.000GB
test 1.208GB
local 1.941GB
> use test; #切换当前数据库,没有时创建
switched to db test
> show collections;
coll1
coll2
> db.help()
DB methods:
db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [ just calls db.runCommand(...) ]
db.auth(username, password)
db.cloneDatabase(fromhost)
db.commandHelp(name) returns the help for the command
db.copyDatabase(fromdb, todb, fromhost)
db.createCollection(name, { size : ..., capped : ..., max : ... } )
db.createView(name, viewOn, [ { $operator: {...}}, ... ], { viewOptions } )
db.createUser(userDocument)
db.currentOp() displays currently executing operations in the db
db.dropDatabase()
db.eval() - deprecated
db.fsyncLock() flush data to disk and lock server for backups
db.fsyncUnlock() unlocks server following a db.fsyncLock()
db.getCollection(cname) same as db['cname'] or db.cname
db.getCollectionInfos([filter]) - returns a list that contains the names and options of the db's collections
db.getCollectionNames()
db.getLastError() - just returns the err msg string
db.getLastErrorObj() - return full status object
db.getLogComponents()
db.getMongo() get the server connection object
db.getMongo().setSlaveOk() allow queries on a replication slave server
db.getName()
db.getPrevError()
db.getProfilingLevel() - deprecated
db.getProfilingStatus() - returns if profiling is on and slow threshold
db.getReplicationInfo()
db.getSiblingDB(name) get the db at the same server as this one
db.getWriteConcern() - returns the write concern used for any operations on this db, inherited from server object if set
db.hostInfo() get details about the server's host
db.isMaster() check replica primary status
db.killOp(opid) kills the current operation in the db
db.listCommands() lists all the db commands
db.loadServerScripts() loads all the scripts in db.system.js
db.logout()
db.printCollectionStats()
db.printReplicationInfo()
db.printShardingStatus()
db.printSlaveReplicationInfo()
db.dropUser(username)
db.repairDatabase()
db.resetError()
db.runCommand(cmdObj) run a database command. if cmdObj is a string, turns it into { cmdObj : 1 }
db.serverStatus()
db.setLogLevel(level,<component>)
db.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=all
db.setWriteConcern( <write concern doc> ) - sets the write concern for writes to the db
db.unsetWriteConcern( <write concern doc> ) - unsets the write concern for writes to the db
db.setVerboseShell(flag) display extra information in shell output
db.shutdownServer()
db.stats()
db.version() current version of the server
> db.foo.help()
DBCollection help
db.foo.find().help() - show DBCursor help
db.foo.bulkWrite( operations, <optional params> ) - bulk execute write operations, optional parameters are: w, wtimeout, j
db.foo.count( query = {}, <optional params> ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS
db.foo.copyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied.
db.foo.convertToCapped(maxBytes) - calls {convertToCapped:'foo', size:maxBytes}} command
db.foo.createIndex(keypattern[,options])
db.foo.createIndexes([keypatterns], <options>)
db.foo.dataSize()
db.foo.deleteOne( filter, <optional params> ) - delete first matching document, optional parameters are: w, wtimeout, j
db.foo.deleteMany( filter, <optional params> ) - delete all matching documents, optional parameters are: w, wtimeout, j
db.foo.distinct( key, query, <optional params> ) - e.g. db.foo.distinct( 'x' ), optional parameters are: maxTimeMS
db.foo.drop() drop the collection
db.foo.dropIndex(index) - e.g. db.foo.dropIndex( "indexName" ) or db.foo.dropIndex( { "indexKey" : 1 } )
db.foo.dropIndexes()
db.foo.ensureIndex(keypattern[,options]) - DEPRECATED, use createIndex() instead
db.foo.explain().help() - show explain help
db.foo.reIndex()
db.foo.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.
e.g. db.foo.find( {x:77} , {name:1, x:1} )
db.foo.find(...).count()
db.foo.find(...).limit(n)
db.foo.find(...).skip(n)
db.foo.find(...).sort(...)
db.foo.findOne([query], [fields], [options], [readConcern])
db.foo.findOneAndDelete( filter, <optional params> ) - delete first matching document, optional parameters are: projection, sort, maxTimeMS
db.foo.findOneAndReplace( filter, replacement, <optional params> ) - replace first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument
db.foo.findOneAndUpdate( filter, update, <optional params> ) - update first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument
db.foo.getDB() get DB object associated with collection
db.foo.getPlanCache() get query plan cache associated with collection
db.foo.getIndexes()
db.foo.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )
db.foo.insert(obj)
db.foo.insertOne( obj, <optional params> ) - insert a document, optional parameters are: w, wtimeout, j
db.foo.insertMany( [objects], <optional params> ) - insert multiple documents, optional parameters are: w, wtimeout, j
db.foo.mapReduce( mapFunction , reduceFunction , <optional params> )
db.foo.aggregate( [pipeline], <optional params> ) - performs an aggregation on a collection; returns a cursor
db.foo.remove(query)
db.foo.replaceOne( filter, replacement, <optional params> ) - replace the first matching document, optional parameters are: upsert, w, wtimeout, j
db.foo.renameCollection( newName , <dropTarget> ) renames the collection.
db.foo.runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name
db.foo.save(obj)
db.foo.stats({scale: N, indexDetails: true/false, indexDetailsKey: <index key>, indexDetailsName: <index name>})
db.foo.storageSize() - includes free space allocated to this collection
db.foo.totalIndexSize() - size in bytes of all the indexes
db.foo.totalSize() - storage allocated for all data and indexes
db.foo.update( query, object[, upsert_bool, multi_bool] ) - instead of two flags, you can pass an object with fields: upsert, multi
db.foo.updateOne( filter, update, <optional params> ) - update the first matching document, optional parameters are: upsert, w, wtimeout, j
db.foo.updateMany( filter, update, <optional params> ) - update all matching documents, optional parameters are: upsert, w, wtimeout, j
db.foo.validate( <full> ) - SLOW
db.foo.getShardVersion() - only for use with sharding
db.foo.getShardDistribution() - prints statistics about data distribution in the cluster
db.foo.getSplitKeysForChunks( <maxChunkSize> ) - calculates split points over all chunks and returns splitter function
db.foo.getWriteConcern() - returns the write concern used for any operations on this collection, inherited from server/db if set
db.foo.setWriteConcern( <write concern doc> ) - sets the write concern for writes to the collection
db.foo.unsetWriteConcern( <write concern doc> ) - unsets the write concern for writes to the collection
db.foo.latencyStats() - display operation latency histograms for this collection
find查询
>db.coll1.find()
{ "_id" : ObjectId("5a030ac4f33db421983b0429"), "plater" : "粤S97R18", "vin" : "LV02214", "breakdown" : [ { "file_id" : "13085", "case_number" : "C519", "lev_code" : "B1", "lev_name_chi" : "电气_发电机", "caller_name" : "丸子", "caller_phone" : "158141", "crdate" : ISODate("2017-11-06T16:00:07Z") } ] }...
>db.coll1.find({'vin':'LV02214'});
>db.coll1.find({'breakdown.file_id':'13085'});
> db.breakdown_case.count()
创建用户
use admin
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
}
)