mongoDB命令学习

MongoDb 命令初学
2010-06-24 10:21
如果想查看当前连接在哪个数据库下面,可以直接输入db

CODE:

> db
Admin
想切换到test数据库下面

CODE:

> use test
switched to db test
> db
Test
想查看test下有哪些表或者叫collection,可以输入

CODE:

> show collections
system.indexes
user
想知道mongodb支持哪些命令,可以直接输入help

CODE:

> help
HELP
      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
      use <db name>                set curent database to <db name>
      db.help()                    help on DB methods
      db.foo.help()                help on collection methods
      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
如果想知道当前数据库支持哪些方法:

CODE:

> db.help();
DB methods:
      db.addUser(username, password) 添加数据库授权用户
      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.currentOp() displays the current operation in the db
      db.dropDatabase()        删除当前数据库
      db.eval_r(func, args) run code server-side
      db.getCollection(cname) same as db['cname'] or db.cname
      db.getCollectionNames()        获取当前数据库的表名
      db.getLastError() - just returns the err msg string
      db.getLastErrorObj() - return full status object
      db.getMongo() get the server connection object
      db.getMongo().setSlaveOk() allow this connection to read from the nonmaster member of a replica pair
      db.getName()
      db.getPrevError()
      db.getProfilingLevel()
      db.getReplicationInfo()
      db.getSisterDB(name) get the db at the same server as this onew
      db.killOp() kills the current operation in the db
      db.printCollectionStats()   打印各表的状态信息
      db.printReplicationInfo()        打印主数据库的复制状态信息
      db.printSlaveReplicationInfo()        打印从数据库的复制状态信息
      db.printShardingStatus()                打印分片状态信息
      db.removeUser(username) 删除数据库用户
      db.repairDatabase() 修复数据库
      db.resetError()
      db.runCommand(cmdObj) run a database command.  if cmdObj is a string, turns it into { cmdObj : 1 }
      db.setProfilingLevel(level) 0=off 1=slow 2=all
      db.shutdownServer()
      db.version() current version of the server
如果想知道当前数据库下的表或者表collection支持哪些方法,可以使用一下命令如:

CODE:

> db.user.help();  user为表名
DBCollection help
      db.foo.count()                统计表的行数
      db.foo.dataSize()        统计表数据的大小
      db.foo.distinct( key ) - eg. db.foo.distinct( 'x' )                按照给定的条件除重
      db.foo.drop() drop the collection 删除表
      db.foo.dropIndex(name)  删除指定索引
      db.foo.dropIndexes() 删除所有索引
      db.foo.ensureIndex(keypattern,options) - options should be an object with these possible fields: name, unique, dropDups  增加索引
      db.foo.find( [query] , [fields]) - first parameter is an optional query filter. second parameter 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]) 根据条件查询只查询一条数据
      db.foo.getDB() get DB object associated with collection  返回表所属的库
      db.foo.getIndexes() 显示表的所有索引
      db.foo.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } ) 根据条件分组
      db.foo.mapReduce( mapFunction , reduceFunction , <optional params> )
      db.foo.remove(query) 根据条件删除数据
      db.foo.renameCollection( newName ) renames the collection  重命名表
      db.foo.save(obj) 保存数据
      db.foo.stats()  查看表的状态
      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]) 根据条件更新数据
      db.foo.validate() - SLOW 验证表的详细信息
      db.foo.getShardVersion() - only for use with sharding
Mongodb的备份工具mongodump

如果想备份数据库test 如:

CODE:

[falcon@www.fwphp.cn  ~/mongodb/bin]$ ./mongodump --help
options:
 --help                   produce help message
 -h [ --host ] arg        mongo host to connect to
 -d [ --db ] arg          database to use
 -c [ --collection ] arg  collection to use (some commands)
 -u [ --username ] arg    username
 -p [ --password ] arg    password
 --dbpath arg             directly access mongod data files in this path,
                         instead of connecting to a mongod instance
 -v [ --verbose ]         be more verbose (include multiple times for more
                         verbosity e.g. -vvvvv)
 -o [ --out ] arg (=dump) output directory
[falcon@www.fwphp.cn  ~/mongodb/bin]$ [color=Blue]./mongodump -d test -o test/[/color]
connected to: 127.0.0.1
DATABASE: test         to         test/test
      test.user to test/test/user.bson
               100000 objects
      test.system.indexes to test/test/system.indexes.bson
               1 objects
[falcon@www.fwphp.cn  ~/mongodb/bin]$ ls
   mongo   mongodump    mongofiles   mongorestore  mongosniff
dump  mongod  mongoexport  mongoimport  mongos     test
MongoDB的数据恢复工具mongorestore

查看test库中的表

CODE:

> show collections
system.indexes
User
删除user表

CODE:

> db.user.drop();
True

> show collections
System.indexes
现在利用mongorestore表恢复刚才利用mongodump备份的数据

CODE:

[falcon@www.fwphp.cn  ~/mongodb/bin]$ ./mongorestore --help
usage: ./mongorestore [options] [directory or filename to restore from]
options:
 --help                  produce help message
 -h [ --host ] arg       mongo host to connect to
 -d [ --db ] arg         database to use
 -c [ --collection ] arg collection to use (some commands)
 -u [ --username ] arg   username
 -p [ --password ] arg   password
 --dbpath arg            directly access mongod data files in this path,
                        instead of connecting to a mongod instance
 -v [ --verbose ]        be more verbose (include multiple times for more
                        verbosity e.g. -vvvvv)

[falcon@www.fwphp.cn  ~/mongodb/bin]$ ./mongorestore -d test -c user test/test/user.bson
connected to: 127.0.0.1
test/test/user.bson
       going into namespace [test.user]

       100000 objects
User表中的10w条记录已经恢复

CODE:

> show collections
system.indexes
user
> db.user.find();
{ "_id" : ObjectId("4b9c8db08ead0e3347000000"), "uid" : 1, "username" : "Falcon.C-1" }
{ "_id" : ObjectId("4b9c8db08ead0e3347010000"), "uid" : 2, "username" : "Falcon.C-2" }
{ "_id" : ObjectId("4b9c8db08ead0e3347020000"), "uid" : 3, "username" : "Falcon.C-3" }
{ "_id" : ObjectId("4b9c8db08ead0e3347030000"), "uid" : 4, "username" : "Falcon.C-4" }
{ "_id" : ObjectId("4b9c8db08ead0e3347040000"), "uid" : 5, "username" : "Falcon.C-5" }
.................
has more

mongodb还提供了HTTP查看运行状态及restfull的接口
默认的访问端口是28017
<think>好的,用户现在需要我介绍一下MongoDB命令大全。之前他问过关于replace操作,现在可能是在学习MongoDB的基础,需要更全面的命令总结。我需要先理清MongoDB的主要命令类别,比如数据库操作、集合操作、文档CRUD、索引、聚合、用户权限等。 用户可能是刚入门的开发者或者学生,想要一个系统的命令参考,方便日常使用。他可能不太清楚MongoDB命令的具体分类,或者需要快速查找某个命令的语法和例子。所以我的回答需要结构清晰,分门别类,每个部分给出常用命令和示例,同时注意中文解释的准确性。 之前回复过replaceOne,现在需要扩展成全面的命令大全。需要注意的是,MongoDB命令很多,不可能全部覆盖,但需要包括最常用的部分,避免信息过载。同时,用户可能希望了解基本操作和进阶功能,比如聚合管道和索引优化。 要确保每个命令的语法正确,例子简单明了,比如插入文档用insertOne,查询用find,更新用updateOne等。还要提醒用户注意不同版本的可能差异,比如MongoDB的某些命令在新版本中可能有变化,或者过时的方法如save()已经不推荐使用。 另外,用户可能对权限管理和聚合操作不太熟悉,这部分需要详细说明,比如创建用户、角色,以及聚合管道的使用场景。索引部分要解释不同类型的索引及其适用情况,帮助用户优化查询性能。 最后,需要总结使用建议,比如先掌握基础CRUD,再学习聚合和索引,提醒用户参考官方文档获取最新信息。整体结构要层次分明,方便用户快速浏览和查找所需命令,同时保持语言简洁,避免冗长。</think>以下为 **MongoDB 常用命令分类总结**,涵盖数据库、集合、文档操作及高级功能: --- ### **一、数据库操作** 1. **查看所有数据库** ```bash show dbs ``` 2. **切换/创建数据库** ```bash use 数据库名 # 若数据库不存在则自动创建 ``` 3. **删除当前数据库** ```bash db.dropDatabase() ``` --- ### **二、集合操作** 1. **查看所有集合** ```bash show collections ``` 2. **创建集合** ```bash db.createCollection("集合名", { 可选参数 }) # 示例:设置固定大小 db.createCollection("logs", { capped: true, size: 100000 }) ``` 3. **删除集合** ```bash db.集合名.drop() ``` --- ### **三、文档 CRUD 操作** #### **1. 插入文档** ```bash db.集合名.insertOne({ 文档 }) # 插入单个文档 db.集合名.insertMany([{文档1}, {文档2}]) # 批量插入 ``` #### **2. 查询文档** ```bash db.集合名.find({ 查询条件 }, { 投影字段 }) # 基础查询 db.集合名.findOne({ 条件 }) # 返回第一条匹配结果 ``` - **条件示例** ```bash # 查询年龄大于25的用户,仅返回name字段 db.users.find({ age: { $gt: 25 } }, { name: 1 }) ``` #### **3. 更新文档** ```bash db.集合名.updateOne({ 条件 }, { $set: {字段: 值} }) # 更新第一个匹配项 db.集合名.updateMany({ 条件 }, { $set: {字段: 值} }) # 批量更新 ``` - **操作符** `$set`(修改字段)、`$unset`(删除字段)、`$inc`(数值增加)等 #### **4. 删除文档** ```bash db.集合名.deleteOne({ 条件 }) # 删除第一条匹配文档 db.集合名.deleteMany({ 条件 }) # 删除所有匹配文档 ``` --- ### **四、索引管理** 1. **创建索引** ```bash db.集合名.createIndex({ 字段: 排序方向 }, { 选项 }) # 示例:为email字段创建唯一索引 db.users.createIndex({ email: 1 }, { unique: true }) ``` 2. **查看索引** ```bash db.集合名.getIndexes() ``` 3. **删除索引** ```bash db.集合名.dropIndex("索引名称") ``` --- ### **五、聚合查询** 1. **基础聚合管道** ```bash db.集合名.aggregate([ { $match: { 条件 } }, # 过滤文档 { $group: { _id: "$字段", 统计字段: { $sum: 1 } } }, # 分组统计 { $sort: { 字段: 1 } } # 排序(1升序,-1降序) ]) ``` 2. **常用聚合操作符** `$sum`, `$avg`, `$max`, `$min`, `$push`, `$project`(字段投影) --- ### **六、用户与权限管理** 1. **创建用户** ```bash use admin db.createUser({ user: "用户名", pwd: "密码", roles: [ { role: "角色", db: "数据库名" } ] }) ``` 2. **常用角色** `read`(只读)、`readWrite`(读写)、`dbAdmin`(数据库管理)、`root`(超级用户) 3. **验证用户** ```bash db.auth("用户名", "密码") ``` --- ### **七、实用工具命令** 1. **统计文档数量** ```bash db.集合名.countDocuments({ 条件 }) ``` 2. **清空集合(保留结构)** ```bash db.集合名.deleteMany({}) # 删除所有文档 ``` 3. **导出/导入数据** ```bash mongodump --db 数据库名 # 导出数据库 mongorestore --db 数据库名 # 导入数据库 ``` --- ### **八、高级功能** 1. **地理空间查询** ```bash db.places.createIndex({ location: "2dsphere" }) # 创建地理索引 db.places.find({ location: { $near: { $geometry: { type: "Point", coordinates: [经度, 纬度] }, $maxDistance: 1000 # 最大距离(米) } } }) ``` 2. **事务支持** ```bash session.startTransaction() try { db.集合名.updateOne(...); db.另一集合名.deleteOne(...); session.commitTransaction(); } catch (error) { session.abortTransaction(); } ``` --- ### **使用建议** 1. **优先使用现代语法** - 弃用旧命令如 `save()`, `count()`,改用 `insertOne()`, `countDocuments()` 等 2. **性能优化** - 高频查询字段必须创建索引 - 避免全集合扫描(如无条件的 `find()`) 3. **安全规范** - 生产环境务必启用身份验证(`--auth` 启动参数) - 限制用户权限至最小必要范围 --- 如需更详细的命令说明,请参考 [MongoDB 官方文档](https://www.mongodb.com/docs/)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值