MongoDB 语法使用小结

MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的
他支持的数据结构非常松散,是类似json的bjson格式,因此可以存储比较复杂的数据类型。Mongo最大的特点是他支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引。 
它的特点是高性能、易部署、易使用,存储数据非常方便。 

1. MongoDB的获取和安装 

(1)获取地址 http://www.mongodb.org/downloads 根据自己需要选择相应的版本,linux下可以使用wget 命令。 
(2)解压 mongodb-win32-i386-1.8.1 
(3)创建数据存放文件夹,mongodb默认的数据目录 /data/db 
C:/> mkdir /data 
C:/> mkdir /data/db 
(4)运行 MongoDB 
mongod.exe - 数据库的服务器端,相当于mysql的 mysqld命令,启动服务器端 
mongo.exe - 数据库的客户端,相当于mysql的mysql命令,打开管理控制台 

启动服务 
mongod.exe --dbpath F:/DataBase/MongoDB/db/ 
--dbpath 数据文件存放路径 
--port 数据服务端口 
C:/> cd /my_mongo_dir/bin 
C:/my_mongo_dir/bin > mongod //启动mongod 服务器,默认的数据库路径 /data/db,端口27071 
启动客户端 
mongo.exe cclove 
cclove 所连接的数据库名称 
C:/> cd /my_mongo_dir/bin 
C:/my_mongo_dir/bin> mongo 

2. 熟悉MongoDB的数据操作语句,类sql 

数据库操作语法 
mongo --path 
db.AddUser(username,password) 添加用户 
db.auth(usrename,password) 设置数据库连接验证 
db.cloneDataBase(fromhost) 从目标服务器克隆一个数据库 
db.commandHelp(name) returns the help for the command 
db.copyDatabase(fromdb,todb,fromhost) 复制数据库fromdb---源数据库名称,todb---目标数据库名称,fromhost---源数据库服务器地址 
db.createCollection(name,{size:3333,capped:333,max:88888}) 创建一个数据集,相当于一个表 
db.currentOp() 取消当前库的当前操作 
db.dropDataBase() 删除当前数据库 
db.eval(func,args) run code server-side 
db.getCollection(cname) 取得一个数据集合,同用法:db['cname'] or db.cname 
db.getCollenctionNames() 取得所有数据集合的名称列表 
db.getLastError() 返回最后一个错误的提示消息 
db.getLastErrorObj() 返回最后一个错误的对象 
db.getMongo() 取得当前服务器的连接对象get the server connection object 
db.getMondo().setSlaveOk() allow this connection to read from then nonmaster membr 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() 停止(杀死)在当前库的当前操作 
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() 返回当前程序的版本信息 

数据集(表)操作语法 
db.linlin.find({id:10}) 返回linlin数据集ID=10的数据集 
db.linlin.find({id:10}).count() 返回linlin数据集ID=10的数据总数 
db.linlin.find({id:10}).limit(2) 返回linlin数据集ID=10的数据集从第二条开始的数据集 
db.linlin.find({id:10}).skip(8) 返回linlin数据集ID=10的数据集从0到第八条的数据集 
db.linlin.find({id:10}).limit(2).skip(8) 返回linlin数据集ID=1=的数据集从第二条到第八条的数据 
db.linlin.find({id:10}).sort() 返回linlin数据集ID=10的排序数据集 
db.linlin.findOne([query]) 返回符合条件的一条数据 
db.linlin.getDB() 返回此数据集所属的数据库名称 
db.linlin.getIndexes() 返回些数据集的索引信息 
db.linlin.group({key:...,initial:...,reduce:...[,cond:...]}) 
db.linlin.mapReduce(mayFunction,reduceFunction,<optional params>) 
db.linlin.remove(query) 在数据集中删除一条数据 
db.linlin.renameCollection(newName) 重命名些数据集名称 
db.linlin.save(obj) 往数据集中插入一条数据 
db.linlin.stats() 返回此数据集的状态 
db.linlin.storageSize() 返回此数据集的存储大小 
db.linlin.totalIndexSize() 返回此数据集的索引文件大小 
db.linlin.totalSize() 返回些数据集的总大小 
db.linlin.update(query,object[,upsert_bool]) 在此数据集中更新一条数据 
db.linlin.validate() 验证此数据集 
db.linlin.getShardVersion() 返回数据集共享版本号 

db.linlin.find({'name':'foobar'}) select * from linlin where name='foobar' 
db.linlin.find() select * from linlin 
db.linlin.find({'ID':10}).count() select count(*) from linlin where ID=10 
db.linlin.find().skip(10).limit(20) 从查询结果的第十条开始读20条数据 select * from linlin limit 10,20 ----------mysql 
db.linlin.find({'ID':{$in:[25,35,45]}}) select * from linlin where ID in (25,35,45) 
db.linlin.find().sort({'ID':-1}) select * from linlin order by ID desc 
db.linlin.distinct('name',{'ID':{$lt:20}}) select distinct(name) from linlin where ID<20 

db.linlin.group({key:{'name':true},cond:{'name':'foo'},reduce:function(obj,prev){prev.msum+=obj.marks;},initial:{msum:0}}) 
select name,sum(marks) from linlin group by name 
db.linlin.find('this.ID<20',{name:1}) select name from linlin where ID<20 

db.linlin.insert({'name':'foobar','age':25}) insert into linlin ('name','age') values('foobar',25) 
db.linlin.insert({'name':'foobar','age':25,'email':'cclove2@163.com'}) 

db.linlin.remove({}) delete * from linlin 
db.linlin.remove({'age':20}) delete linlin where age=20 
db.linlin.remove({'age':{$lt:20}}) delete linlin where age<20 
db.linlin.remove({'age':{$lte:20}}) delete linlin where age<=20 
db.linlin.remove({'age':{$gt:20}}) delete linlin where age>20 
db.linlin.remove({'age':{$gte:20}}) delete linlin where age>=20 
db.linlin.remove({'age':{$ne:20}}) delete linlin where age!=20 

db.linlin.update({'name':'foobar'},{$set:{'age':36}}) update linlin set age=36 where name='foobar' 
db.linlin.update({'name':'foobar'},{$inc:{'age':3}}) update linlin set age=age+3 where name='foobar' 

官方提供的操作语句对照表: 

上行:SQL 操作语句 
下行:Mongo 操作语句 
CREATE TABLE USERS (a Number, b Number) 
db.createCollection("mycoll") 

INSERT INTO USERS VALUES(1,1) 
db.users.insert({a:1,b:1}) 

SELECT a,b FROM users 
db.users.find({}, {a:1,b:1}) 

SELECT * FROM users 
db.users.find() 

SELECT * FROM users WHERE age=33 
db.users.find({age:33}) 

SELECT a,b FROM users WHERE age=33 
db.users.find({age:33}, {a:1,b:1}) 

SELECT * FROM users WHERE age=33 ORDER BY name 
db.users.find({age:33}).sort({name:1}) 

SELECT * FROM users WHERE age>33 
db.users.find({'age':{$gt:33}})}) 

SELECT * FROM users WHERE age<33 
db.users.find({'age':{$lt:33}})}) 

SELECT * FROM users WHERE name LIKE "%Joe%" 
db.users.find({name:/Joe/}) 

SELECT * FROM users WHERE name LIKE "Joe%" 
db.users.find({name:/^Joe/}) 

SELECT * FROM users WHERE age>33 AND age<=40 
db.users.find({'age':{$gt:33,$lte:40}})}) 

SELECT * FROM users ORDER BY name DESC 
db.users.find().sort({name:-1}) 

SELECT * FROM users WHERE a=1 and b='q' 
db.users.find({a:1,b:'q'}) 

SELECT * FROM users LIMIT 10 SKIP 20 
db.users.find().limit(10).skip(20) 

SELECT * FROM users WHERE a=1 or b=2 
db.users.find( { $or : [ { a : 1 } , { b : 2 } ] } ) 

SELECT * FROM users LIMIT 1 
db.users.findOne() 

SELECT DISTINCT last_name FROM users 
db.users.distinct('last_name') 

SELECT COUNT(*y) FROM users 
db.users.count() 

SELECT COUNT(*y) FROM users where AGE > 30 
db.users.find({age: {'$gt': 30}}).count() 

SELECT COUNT(AGE) from users 
db.users.find({age: {'$exists': true}}).count() 

CREATE INDEX myindexname ON users(name) 
db.users.ensureIndex({name:1}) 

CREATE INDEX myindexname ON users(name,ts DESC) 
db.users.ensureIndex({name:1,ts:-1}) 

EXPLAIN SELECT * FROM users WHERE z=3 
db.users.find({z:3}).explain() 

UPDATE users SET a=1 WHERE b='q' 
db.users.update({b:'q'}, {$set:{a:1}}, false, true) 

UPDATE users SET a=a+2 WHERE b='q' 
db.users.update({b:'q'}, {$inc:{a:2}}, false, true) 

DELETE FROM users WHERE z="abc" 
db.users.remove({z:'abc'});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MongoDB语法是用于在MongoDB数据库中执行操作的语法规则。其中一些常见的语法包括: 1. 数据库链接:用于建立与MongoDB数据库的连接。可以使用MongoDB连接字符串或MongoDB连接对象来进行连接。 2. 条件操作符:用于比较和筛选集合中的数据。常见的条件操作符包括大于($gt)、小于($lt)、大于等于($gte)、小于等于($lte)、等于($eq)和非等于($ne)等。 3. 插入数据:使用insert()方法向集合中插入数据。可以使用语法格式如下:db.集合名.insert({字段名: 值})。 总结起来,MongoDB语法包括数据库链接、条件操作符和插入数据等基本操作。使用这些语法可以对MongoDB数据库进行增删改查等操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [MongoDB 语法大全](https://blog.csdn.net/weixin_38316697/article/details/126085968)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [【数据库】——MongoDB常用语法](https://blog.csdn.net/weixin_44697562/article/details/110122105)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值