MongoDB的常用命令和增查改删
|
数据库操作 |
Mongodb |
MySQL |
|
查询库 |
show databases | show dbs |
show databases |
|
选中库 |
use databaseName |
use databaseName |
|
查询表 |
show tables | show collections |
show tables |
|
创建表 |
db.createCollection(‘collectionName’) |
create table tableName... |
|
删除表 |
db.collectionName.drop |
drop table tableName |
|
删除库 |
db.dropDatabase |
drop database databaseName |
|
添加表数据 |
db.collectionName.insert |
insert |
|
查询表数据 |
db.collectionName.find |
select |
|
修改表数据 |
db.collectionName.update |
update |
|
删除表数据 |
db.collectionName.remove |
delete |
如上述所示,mongodb同样兼容了部分传统数据库的命令,其中有必要说一下的是mongodb中创建库采用的是隐式创建,即在use 一个不存在的库时就会变为创建库,use databaseName 有则选中无则创建,但这里还没有创建完毕,需要进一步创建表才算创建完毕;同时创建表时也允许隐式创建,即db.collectionName.insert 往一个不存在的表中添加数据就会先创建表再添加数据
一:常用命令
1.1:查看当前的数据库
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
shop 0.000GB
> show databases
admin 0.000GB
config 0.000GB
local 0.000GB
shop 0.000GB
1.2:选中库
> use shop
switched to db shop
1.3:查看表
> show collections
user
> show tables
user
1.4.1:创建库/表
> use good
switched to db good
> db.createCollection('items')
{ "ok" : 1 }
1.4.2:创建库/表第二种方式
> use cate
switched to db cate
> db.cateList.insert({"_id":1,"cateName":"FAST"})
WriteResult({ "nInserted" : 1 })
1.4.3:在创建库时如果没有创建表,库也会创建失败
> use cate
switched to db cate
> show dbs
admin 0.000GB
config 0.000GB
good 0.000GB
local 0.000GB
shop 0.000GB
1.5:删除表
> db.cateList.drop()
true
1.6:删除库
> use good
switched to db good
> db.dropDatabase()
{ "dropped" : "good", "ok" : 1 }
1.7:使用db.help()查看更多方法
> db.help()
DB methods:
db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [just calls db.runCommand(...)]
db.aggregate([pipeline], {options}) - performs a collectionless aggregation on this database; returns a cursor
db.auth(username, password)
db.cloneDatabase(fromhost) - deprecated
db.commandHelp(name) returns the help for the command
db.copyDatabase(fromdb, todb, fromhost) - deprecated
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.collectionName.insert(document);
2.1: 增加单篇文档,如果未指定_id会自动生成:
> use shop
switched to db shop
> db.createCollection('order')
{ "ok" : 1 }
> db.order.insert({"orderCode":"F3K32IR45O","price":150.00})
WriteResult({ "nInserted" : 1 })
> db.order.find()
{ "_id" : ObjectId("5c233308a479af93b5192daa"), "orderCode" : "F3K32IR45O", "price" : 150 }
2.2:增加单个文档并指定_id
> db.order.insert({"_id":2,"orderCode":"F3K32IR45O","price":150.00})
WriteResult({ "nInserted" : 1 })
> db.order.find()
{ "_id" : ObjectId("5c233308a479af93b5192daa"), "orderCode" : "F3K32IR45O", "price" : 150 }
{ "_id" : 2, "orderCode" : "F3K32IR45O", "price" : 150 }
2.3:增加多个文档
> db.order.insert([{"orderCode":"F3K32IR41O","price":1020.00},{"_id":4,"orderCode":"EW3213FW1324","price":11.11}])
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
> db.order.find()
{ "_id" : ObjectId("5c233308a479af93b5192daa"), "orderCode" : "F3K32IR45O", "price" : 150 }
{ "_id" : 2, "orderCode" : "F3K32IR45O", "price" : 150 }
{ "_id" : ObjectId("5c2334cca479af93b5192dac"), "orderCode" : "F3K32IR41O", "price" : 1020 }
{ "_id" : 4, "orderCode" : "EW3213FW1324", "price" : 11.11 }
2.4:在mongodb3.2版本中新增两个插入方法:
db.collection.insertOne() //将单个文档插入集合中
db.collection.insertMany() //将多个文档插入集合中
三:查:db.collection.find(查询表达式,查询的属性);
3.1:查询所有数据
> db.order.find()
{ "_id" : ObjectId("5c233308a479af93b5192daa"), "orderCode" : "F3K32IR45O", "price" : 150 }
{ "_id" : 2, "orderCode" : "F3K32IR45O", "price" : 150 }
{ "_id" : ObjectId("5c2334cca479af93b5192dac"), "orderCode" : "F3K32IR41O", "price" : 1020 }
{ "_id" : 4, "orderCode" : "EW3213FW1324", "price" : 11.11 }
3.2:查询所有文档的指定属性(_id属性默认查询)
> db.order.find({},{orderCode:1})
{ "_id" : ObjectId("5c233308a479af93b5192daa"), "orderCode" : "F3K32IR45O" }
{ "_id" : 2, "orderCode" : "F3K32IR45O" }
{ "_id" : ObjectId("5c2334cca479af93b5192dac"), "orderCode" : "F3K32IR41O" }
{ "_id" : 4, "orderCode" : "EW3213FW1324" }
3.3:查询所有文档的指定属性且不查询_id
> db.order.find({},{orderCode:1,_id:0}) #属性为1表示查询,为0表示过滤
{ "orderCode" : "F3K32IR45O" }
{ "orderCode" : "F3K32IR45O" }
{ "orderCode" : "F3K32IR41O" }
{ "orderCode" : "EW3213FW1324" }
3.4:查询所有orderCode属性值为F3K32IR45O的文档中的price属性且不查询_id属性
> db.order.find({"orderCode":"F3K32IR45O"},{"price":1,_id:0})
{ "price" : 150 }
{ "price" : 150 }
3.5:比较查询运算符
3.5.1: $gt(大于)
> db.order.find({"price":{$gt:150}},{"orderCode":1,"price":1,"_id":0})
{ "orderCode" : "F3K32IR41O", "price" : 1020 }
3.5.2:$gte(大于等于)
> db.order.find({"price":{$gte:150}},{"orderCode":1,"price":1,"_id":0})
{ "orderCode" : "F3K32IR45O", "price" : 150 }
{ "orderCode" : "F3K32IR45O", "price" : 150 }
{ "orderCode" : "F3K32IR41O", "price" : 1020 }
3.5.3:$lt(小于)
> db.order.find({"price":{$lt:150}},{"orderCode":1,"price":1,"_id":0})
{ "orderCode" : "EW3213FW1324", "price" : 11.11 }
3.5.4:$lte(小于等于)
> db.order.find({"price":{$lte:150}},{"orderCode":1,"price":1,"_id":0})
{ "orderCode" : "F3K32IR45O", "price" : 150 }
{ "orderCode" : "F3K32IR45O", "price" : 150 }
{ "orderCode" : "EW3213FW1324", "price" : 11.11 }
3.5.5:$eq(等于)
> db.order.find({"price":{$eq:150}},{"orderCode":1,"price":1,"_id":0})
{ "orderCode" : "F3K32IR45O", "price" : 150 }
{ "orderCode" : "F3K32IR45O", "price" : 150 }
#or
> db.order.find({"price":150},{"orderCode":1,"price":1,"_id":0})
{ "orderCode" : "F3K32IR45O", "price" : 150 }
{ "orderCode" : "F3K32IR45O", "price" : 150 }
3.5.6:$ne(不等于)
> db.order.find({"price":{$ne:150}},{"orderCode":1,"price":1,"_id":0})
{ "orderCode" : "F3K32IR41O", "price" : 1020 }
{ "orderCode" : "EW3213FW1324", "price" : 11.11 }
3.5.7:$in(数组中指定的任何值,相当于MySQL的in)
> db.order.find({"price":{$in:[11.11,1020]}},{"orderCode":1,"price":1,"_id":0})
{ "orderCode" : "F3K32IR41O", "price" : 1020 }
{ "orderCode" : "EW3213FW1324", "price" : 11.11 }
3.5.8:$nin(不在指定的数组中)
> db.order.find({"price":{$nin:[150,1020]}},{"orderCode":1,"price":1,"_id":0})
{ "orderCode" : "EW3213FW1324", "price" : 11.11 }
3.6:逻辑查询运算符
3.6.1:$and(连接查询子句)
> db.order.find({$and:[{"orderCode":"F3K32IR45O"},{"price":150}]},{"orderCode":1,"price":1,"_id":0})
{ "orderCode" : "F3K32IR45O", "price" : 150 }
{ "orderCode" : "F3K32IR45O", "price" : 150 }
3.6.2:$not(返回不匹配指定条件的文档)
> db.order.find({"price":{$not:{$gte:150}}},{"orderCode":1,"price":1,"_id":0}) #返回price不大于等于150的文档,也就是返回price小于150的文档
{ "orderCode" : "EW3213FW1324", "price" : 11.11 }
3.6.3:$nor(连接查询子句并返回所有无法匹配指定条件的文档)
> db.order.find({$nor:[{"orderCode":"F3K32IR45O"},{"price":150}]},{"orderCode":1,"price":1,"_id":0}) #返回orderCode不等于F3K32IR45O并且price不等于150的文档
{ "orderCode" : "F3K32IR41O", "price" : 1020 } { "orderCode" : "EW3213FW1324", "price" : 11.11 }
3.6.4:$or(返回匹配任一条件的文档,相当于MySQL的or)
> db.order.find({$or:[{"price":11.11},{"price":1020}]},{"orderCode":1,"price":1,"_id":0})
{ "orderCode" : "F3K32IR41O", "price" : 1020 }
{ "orderCode" : "EW3213FW1324", "price" : 11.11 }
3.7:元素查询运算符
3.7.1:$exists(匹配具有指定字段的文档)
> db.order.find({"price":{$exists:true}},{"orderCode":1,"price":1,"_id":0}) #$exists为true匹配具有指定字段的文档
{ "orderCode" : "F3K32IR45O", "price" : 150 }
{ "orderCode" : "F3K32IR45O", "price" : 150 }
{ "orderCode" : "F3K32IR41O", "price" : 1020 }
{ "orderCode" : "EW3213FW1324", "price" : 11.11 }
> db.order.find({"price":{$exists:false}},{"orderCode":1,"price":1,"_id":0}) #$exists为false匹配不具有指定字段的文档
3.7.2:$type(匹配指定类型的文档) 可选类型点我
> db.order.find({"orderCode":{$type:2}},{"orderCode":1,"price":1,"_id":0}) #$type可使用数字别名 2表示字符串
{ "orderCode" : "F3K32IR45O", "price" : 150 }
{ "orderCode" : "F3K32IR45O", "price" : 150 }
{ "orderCode" : "F3K32IR41O", "price" : 1020 }
{ "orderCode" : "EW3213FW1324", "price" : 11.11 }
3.8:$regex(正则匹配)
> db.order.find({"orderCode":{$regex:/^E/}},{"orderCode":1,"price":1,"_id":0})
{ "orderCode" : "EW3213FW1324", "price" : 11.11 }
3.9:findOne(查询单个文档)
> db.order.findOne({"orderCode":"F3K32IR45O"},{"orderCode":1,"price":1,"_id":0})
{ "orderCode" : "F3K32IR45O", "price" : 150 }
四:改:db.user.update(查询表达式,修改的新值,选项{upsert:true/false,multi:true/false})
4.1:$set(设置文档中字段的值,如果设置的字段不存在则创建该字段)
> db.order.update({_id:4},{$set:{"orderCode":"WFIQ13U321UE2","price":111}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.order.find({_id:4})
{ "_id" : 4, "orderCode" : "WFIQ13U321UE2", "price" : 111 }
4.2:$unset(删除指定字段)
> db.order.update({_id:4},{$unset:{"orderCode":""}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
4.3:$inc(按指定的数量增加字段的值)
{ "_id" : 4, "price" : 111, "type" : 1 }
> db.order.update({_id:4},{$inc:{"price":2}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.order.find({_id:4})
{ "_id" : 4, "price" : 113, "type" : 1 }
4.4:$min(指定值小于现有字段值才更新,当指定的字段不存在时变为设置该字段为指定的值)
> db.order.update({_id:4},{$min:{"price":110}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.order.find({_id:4})
{ "_id" : 4, "price" : 110, "type" : 1 }
4.6:$max(指定值大于现有字段值才更新,当指定的字段不存在时变为设置该字段为指定的值)
> db.order.update({_id:4},{$max:{"price":120}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.order.find({_id:4})
{ "_id" : 4, "price" : 120, "type" : 1 }
4.7:$mul(将字段的值乘以指定的值)
> db.order.update({_id:4},{$mul:{"price":2}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.order.find({_id:4})
{ "_id" : 4, "price" : 240, "type" : 1 }
4.8:$rename(重命名字段)
> db.order.update({_id:4},{$rename:{"price":"money"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.order.find({_id:4})
{ "_id" : 4, "type" : 1, "cate" : 0, "money" : 240 }
4.9:在mongodb3.2版本中新增三个修改方法:
db.collection.updateOne() //更新与指定过滤器匹配的单个文档
db.collection.updateMany() //更新与指定过滤器匹配的所有文档
db.collection.replaceOne() //替换与指定过滤器匹配的单个文档
4.10:带可选条件的修改操作(upsert:true/false,multi:true/false)
--upsert 默认为false,无相应记录时是否添加
--multi 默认为false, 是否作用于多条
> db.order.update({},{$set:{"price":2000}},{upsert:true,multi:true})
WriteResult({ "nMatched" : 4, "nUpserted" : 0, "nModified" : 4 })
> db.order.find()
{ "_id" : ObjectId("5c233308a479af93b5192daa"), "price" : 2000 }
{ "_id" : 2, "orderCode" : "F3K32IR45O", "price" : 2000 }
{ "_id" : ObjectId("5c2334cca479af93b5192dac"), "orderCode" : "F3K32IR41O", "price" : 2000 }
{ "_id" : 4, "price" : 2000 }
五:删除: db.collection.remove(查询表达式, 选项{justOne:true/flase})
5.1:删除指定查询条件的所有文档
> db.order.remove({"_id":4})
WriteResult({ "nRemoved" : 1 })
> db.order.find()
{ "_id" : ObjectId("5c233308a479af93b5192daa"), "price" : 2000 }
{ "_id" : 2, "orderCode" : "F3K32IR45O", "price" : 2000 }
{ "_id" : ObjectId("5c2334cca479af93b5192dac"), "orderCode" : "F3K32IR41O", "price" : 2000 }
5.2:删除指定查询条件中所有文档的第一个即指定可选参数justOne:true
> db.order.remove({},true)
WriteResult({ "nRemoved" : 1 })
> db.order.find()
{ "_id" : 2, "price" : 1000 }
{ "_id" : 3, "price" : 1000 }
{ "_id" : 4, "price" : 1000 }
5.3:在mongodb3.2版本中新增两个删除方法:
db.collection.deleteOne() #删除与指定过滤器匹配的单个文档
db.collection.deleteMany() #删除与指定过滤器匹配的所有文档
MongoDB的常用命令和增查改删的更多相关文章
- EF里单个实体的增查改删以及主从表关联数据的各种增删 改查
本文目录 EF对单个实体的增查改删 增加单个实体 查询单个实体 修改单个实体 删除单个实体 EF里主从表关联数据的各种增删改查 增加(增加从表数据.增加主从表数据) 查询(根据主表找从表数据.根据从表 ...
- SQL Server 2012 学习笔记3 增查改删
现在举例几个"增查改删"的语句 select * from UserInfor --查找所有字段 select username,UserId from UserInfor -- ...
- ylb:创建数据库、表,对表的增查改删语句
ylbtech-SQL Server:SQL Server-创建数据库.表,对表的增查改删语句 SQL Server 创建数据库.表,对表的增查改删语句. 1,ylb:创建数据库.表,对表的增查改删语 ...
- DOM树的增查改删总结
DOM树的增查改删总结 摘要:对HTML DOM的操作是前端JavaScript编程时必备的技能,本文是我自己对DOM树操作的总结,主要是方法的罗列,原理性的讲述较少,适合大家用于理清思路或是温习 一 ...
- JS 数组, 对象的增查改删(多语法对比)
数据结构横向对比, 增, 查, 改, 删 建议: 在用数据结构的时候, 优先考虑Map和Set(考虑数据的唯一性), 放弃传统的数组和Object, 特别是比较复杂的数据结构时 数组 Map与Arra ...
- mongodb 增查改删
我们在 MongoDB 之 你得知道MongoDB是个什么鬼 MongoDB - 1 中学习了如果安装部署一个 MongoDB 如果没看到我的金玉良言的话,就重新打开一次客户端和服务端吧 本章我们 ...
- MongoDB入门 常用命令以及增删改查的简单操作
1,运行MongoDB服务mongod --dbpath=/usr/local/developmentTool/mongo/data/db/然后启动客户端mongo2,sudo service mon ...
- MongoDB学习记录(四) - MongoDB的"增查改删"操作之"改"
更新文档主要有以下几种方法: db.collection.updateOne(filter, update, options) db.collection.updateMany(filter, upd ...
- php 连接mongodb 增查改删操作
查询 <?php $m=new MongoClient('mongodb://admin:admin@localhost:27017/admin'); $db=$m->hndb; $cc= ...
随机推荐
- Web系统大规模并发:电商秒杀与抢购-----面试必问
一.大规模并发带来的挑战 在过去的工作中,我曾经面对过5w每秒的高并发秒杀功能,在这个过程中,整个Web系统遇到了很多的问题和挑战.如果Web系统不做针对性的优化,会轻而易举地陷入到异常状态.我们现在 ...
- 并发编程(十二)—— Java 线程池 实现原理与源码深度解析 之 submit 方法 (二)
在上一篇<并发编程(十一)—— Java 线程池 实现原理与源码深度解析(一)>中提到了线程池ThreadPoolExecutor的原理以及它的execute方法.这篇文章是接着上一篇文章 ...
- MongoDB exception:connection failed
根据http://www.runoob.com/mongodb/mongodb-window-install.html的教程配置了MongoDB,Mongod.exe配置为 --port 指令表明mo ...
- redis 系列10 字符串对象
一. 字符串对象编码 Redis中字符串可以存储3种类型,分别是字节串(byte string).整数.浮点数.在上章节中讲到字符串对象的编码可以是int, raw,embstr. 如果一个字符串对象 ...
- Spring Cloud中的负载均衡策略
在上篇博客(Spring Cloud中负载均衡器概览)中,我们大致的了解了一下Spring Cloud中有哪些负载均衡器,但是对于负载均衡策略我们并没有去详细了解,我们只是知道在BaseLoadBal ...
- 设计模式总结篇系列:组合模式(Composite)
在探讨Java组合模式之前,先要明白几个概念的区别:继承.组合和聚合. 继承是is-a的关系.组合和聚合有点像,有些书上没有作区分,都称之为has-a,有些书上对其进行了较为严格区分,组合是conta ...
- C#线程安全使用(一)
关于Task的使用,一直都是半知半解,最近终于有时间详细的看了一遍MSDN,作为备忘录,将心得也记录下来和大家分享. 首先,根据MSDN的描述,Task是FrameWork4引进的新功能,他和ConC ...
- HDFS架构及原理
原文链接:HDFS架构及原理 引言 进入大数据时代,数据集的大小已经超过一台独立物理计算机的存储能力,我们需要对数据进行分区(partition)并存储到若干台单独的计算机上,也就出现了管理网络中跨多 ...
- Python3+Selenium2完整的自动化测试实现之旅(四):Selenium-webdriver操作浏览器、Cookie、鼠标键盘、警示框、设置等待时间、多窗口切换
本篇学习总结webdriver模块操作浏览器.Cookie.鼠标键盘.警示框.设置等待时间.多窗口切换等方法的使用 1 浏览器控制 Selenium-webdriverAPI提供了对页面元素定位 ...
- [转]【翻译】在Visual Studio中使用Asp.Net Core MVC创建你的第一个Web API应用(一)
本文转自:https://www.cnblogs.com/inday/p/6288707.html HTTP is not just for serving up web pages. It’s al ...