命令mongo 可以与数据库建立连接并操作数据库。
${MongoDB_HOME}/bin目录下执行: ./mongo --help MongoDB shell version v3.4.0 usage: ./mongo [options] [db address] [file names (ending in .js)] db address can be: foo foo database on local machine 192.168.0.5/foo foo database on 192.168.0.5 machine 192.168.0.5:9999/foo foo database on 192.168.0.5 machine on port 9999 Options: --shell run the shell after executing files --nodb don't connect to mongod on startup - no 'db address' arg expected --norc will not run the ".mongorc.js" file on start up --quiet be less chatty --port arg port to connect to --host arg server to connect to --eval arg evaluate javascript -h [ --help ] show this usage information --version show version information --verbose increase verbosity --ipv6 enable IPv6 support (disabled by default) --disableJavaScriptJIT disable the Javascript Just In Time compiler --disableJavaScriptProtection allow automatic JavaScript function marshalling --ssl use SSL for all connections --sslCAFile arg Certificate Authority file for SSL --sslPEMKeyFile arg PEM certificate/key file for SSL --sslPEMKeyPassword arg password for key in PEM file for SSL --sslCRLFile arg Certificate Revocation List file for SSL --sslAllowInvalidHostnames allow connections to servers with non-matching hostnames --sslAllowInvalidCertificates allow connections to servers with invalid certificates --sslFIPSMode activate FIPS 140-2 mode at startup --networkMessageCompressors arg Comma-separated list of compressors to use for network messages --jsHeapLimitMB arg set the js scope's heap size limit Authentication Options: -u [ --username ] arg username for authentication -p [ --password ] arg password for authentication --authenticationDatabase arg user source (defaults to dbname) --authenticationMechanism arg authentication mechanism --gssapiServiceName arg (=mongodb) Service name to use when authenticating using GSSAPI/Kerberos --gssapiHostName arg Remote host name to use for purpose of GSSAPI/Kerberos authentication file names: a list of files to run. files have to end in .js and will exit after unless --shell is specified
简单示例:
./mongo 127.0.0.1:27017/local
连接本机端口27017上的mongdb数据库,并打开local数据库。
./mongo 127.0.0.1:27017
>use mydb //打开数据库,如果不存在该数据库则新建一个并打开数据库
switched to db mydb
>show dbs //显示数据库
admin
local //由于mydb 新建的数据库,无数据,所不未显示
>db //查看当前数据库
mydb
>show collections //查看当前库下所有集合
> //, 新建库无集合,所以未显示
>help//显示控制台命令:
db.help() help on db methods
db.mycoll.help() help on collection methods
sh.help() sharding helpers
rs.help() replica set helpers
help admin administrative help
help connect connecting to a db help
help keys key shortcuts
help misc misc things to know
help mr mapreduce
show dbs show database names
show collections show collections in current database
show users show users in current database
show profile show most recent system.profile entries
with time >= 1ms
show logs show the accessible logger names
show log [name] prints out the last segment of log in
memory, 'global' is default
use <db_name> set current database
db.foo.find() list objects in collection foo
db.foo.find( { a : 1 } ) list objects in foo where a == 1
it result of the last line evaluated; use to
further iterate
DBQuery.shellBatchSize = x set default number of items to display on
shell
exit quit the mongo shell
>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.mycollection.help()//显示集合的支持的操作 mycoll为集合的名字
DBCollection help
db.mycollection.find().help() - show DBCursor help
db.mycollection.bulkWrite( operations, <optional params> )
- bulk execute write operations,
optional parameters are: w, wtimeout, j
db.mycollection.count( query = {}, <optional params> )
- count the number of documents that matches the
query, optional parameters are: limit, skip, hint,maxTimeMS
db.mycollection.copyTo(newColl) - duplicates collection by c
opying all documents to newColl; no indexes are copied.
db.mycollection.convertToCapped(maxBytes) - calls
{convertToCapped:'user', size:maxBytes}} command
db.mycollection.createIndex(keypattern[,options])
db.mycollection.createIndexes([keypatterns], <options>)
db.mycollection.dataSize()
db.mycollection.deleteOne( filter, <optional params> )
- delete first matching document, optional parameters are: w, wtimeout, j
db.mycollection.deleteMany( filter, <optional params> )
- delete all matching documents, optional parameters are: w, wtimeout, j
db.mycollection.distinct( key, query, <optional params> )
- e.g. db.mycollection.distinct( 'x' ), optional parameters are: maxTimeMS
db.mycollection.drop() drop the collection
db.mycollection.dropIndex(index)
- e.g. db.mycollection.dropIndex( "indexName" ) or
db.mycollection.dropIndex( { "indexKey" : 1 } )
db.mycollection.dropIndexes()
db.mycollection.ensureIndex(keypattern[,options]) - DEPRECATED,
usecreateIndex() instead
db.mycollection.explain().help() - show explain help
db.mycollection.reIndex()
db.mycollection.find([query],[fields]) - query is an
optional query filter.fields is optional set of fields to return.
e.g. db.mycollection.find({x:77} , {name:1, x:1} )
db.mycollection.find(...).count()
db.mycollection.find(...).limit(n)
db.mycollection.find(...).skip(n)
db.mycollection.find(...).sort(...)
db.mycollection.findOne([query], [fields], [options], [readConcern])
db.mycollection.findOneAndDelete( filter, <optional params> )
- delete first matching document, optional parameters are
: projection, sort, maxTimeMS
db.mycollection.findOneAndReplace( filter, replacement,
<optional params> ) -replace first matching document,
optional parameters are: projection, sort,maxTimeMS, upsert,
returnNewDocument
db.mycollection.findOneAndUpdate( filter, update, <optional params> )
- updatefirst matching document, optional parameters are:
projection, sort, maxTimeMS,upsert, returnNewDocument
db.mycollection.getDB() get DB object associated with collection
db.mycollection.getPlanCache() get query plan cache
associated with collection
db.mycollection.getIndexes()
db.mycollection.group( { key : ..., initial: ..., reduce : ...[, cond: ...] })
db.mycollection.insert(obj)
db.mycollection.insertOne( obj, <optional params> )
- insert a document,optional parameters are: w, wtimeout, j
db.mycollection.insertMany( [objects], <optional params> )
- insert multipledocuments, optional parameters are: w, wtimeout, j
db.mycollection.mapReduce( mapFunction , reduceFunction , <optional params> )
db.mycollection.aggregate( [pipeline], <optional params> )
- performs anaggregation on a collection; returns a cursor
db.mycollection.remove(query)
db.mycollection.replaceOne( filter, replacement, <optional params> )
- replacethe first matching document, optional parameters are:
upsert, w, wtimeout, j
db.mycollection.renameCollection( newName , <dropTarget> ) renames thecollection.
db.mycollection.runCommand( name , <options> ) runs a db
command with thegiven name where the
first param is the collection name
db.mycollection.save(obj)
db.mycollection.stats({scale: N, indexDetails: true/false,
indexDetailsKey:<index key>, index DetailsName: <index name>})
db.mycollection.storageSize() - includes free space allocated to this collection
db.mycollection.totalIndexSize() - size in bytes of all the indexes
db.mycollection.totalSize() - storage allocated for all data and indexes
db.mycollection.update( query, object[, upsert_bool, multi_bool] )
- instead of two flags, you can pass an object
with fields: upsert, multi
db.mycollection.updateOne( filter, update, <optional params> )
- update the first matching document, optional parameters are:
upsert, w, wtimeout, j
db.mycollection.updateMany( filter, update, <optional params> )
- update all matching documents, optional parameters are:
upsert, w, wtimeout, j
db.mycollection.validate( <full> ) - SLOW
db.mycollection.getShardVersion() - only for use with sharding
db.mycollection.getShardDistribution() - prints statistics
about data distribution in the cluster
db.mycollection.getSplitKeysForChunks( <maxChunkSize> )
- calculates split points over all
chunks and returns splitter function
db.mycollection.getWriteConcern() - returns the write
concern used for any operations on this collection,
inherited from server/db if set
db.mycollection.setWriteConcern( <write concern doc> )
- sets the write concern for writes to the collection
db.mycollection.unsetWriteConcern( <write concern doc> )
- unsets the write concern for writes to the collection
db.mycollection.latencyStats()
- display operation latency histograms for this collection
相关推荐
MongoVUE 是一款适用于Windows操作系统的MongoDB窗口化应用程序,它使得您能够非常容易的操作MongoDb数据库的同时熟悉MongoDb的命令行。
在Windows操作系统上,为了方便管理和操作MongoDB数据库,有许多客户端工具可供选择,其中之一便是免安装版的MongoDB Windows客户端。 这个“mongodb windows客户端-免安装版”是一款专为Windows用户设计的轻量级...
在 Scala 中与 MongoDB 进行交互,通常我们会使用 `mongo-scala-driver`,而不是 `mongo-java-driver`,因为 Scala 驱动提供了更符合 Scala 语言特性的 API 设计。本示例将详细介绍如何使用 `mongo-scala-driver` ...
5. 使用MongoDB的shell客户端(mongo.exe)连接数据库,进行数据操作和管理。 MongoDB广泛应用于互联网、物联网、大数据分析、内容管理系统等领域,其灵活性和高性能使其成为现代Web应用和实时分析的理想选择。对于...
6. **运行MongoDB**:在Windows环境下,你可以找到解压后的bin目录,其中包含mongod.exe(数据库服务器)和mongo.exe(命令行客户端)。启动mongod服务,需要通过命令行指定数据存储目录,如`mongod --dbpath "C:\...
总的来说,"mongodb-async-driver-2.0.1.jar"这个包是Java开发者与MongoDB数据库交互的强大工具,它通过异步I/O和事件驱动的编程模型,提高了应用的并发能力和响应速度。通过这个驱动,开发者可以充分利用MongoDB的...
MongoDB Go驱动器是MongoDB官方支持的Go语言客户端库,用于与MongoDB数据库进行交互。这个开源项目,"mongodb/mongo-go-driver",提供了一种高效、灵活且功能丰富的接口,让Go开发者能够轻松地在他们的应用中集成...
这个目录将用来存储MongoDB数据库的数据文件。如果没有预先创建,MongoDB在启动时会自动尝试创建,但在某些情况下可能会因为权限问题失败。 3. **配置MongoDB** MongoDB的配置文件通常命名为`mongod.cfg`,但在这...
安装完成后,可以通过MongoDB的命令行客户端`mongo`与数据库交互,执行CRUD(创建、读取、更新、删除)操作。此外,还可以利用各种语言的驱动程序(如Python、Java、Node.js等)在应用程序中连接和操作MongoDB数据库...
8. **监控与管理工具**:MongoDB提供了一套强大的管理工具,如`mongo`命令行客户端和`MongoDB Management Service (MMS)`,用于监控数据库性能、备份恢复等任务。 9. **社区与生态**:MongoDB拥有活跃的开发者社区...
MongoDB是一款开源、分布式、高性能的NoSQL数据库,特别适合...用户只需按照步骤进行解压、配置、启动,就能在Windows系统上顺利运行和管理MongoDB数据库。在实际应用中,应充分利用其特性,进行高效的数据存储和处理。
安装MongoDB时,解压"mongodb-win32-x86_64-2008plus-2.6.0.zip"后,你会找到包含bin目录的文件结构,其中包含了服务器端进程mongod.exe、客户端工具mongoshell.exe以及其他辅助工具。安装过程通常包括配置数据目录...