Mongodb语法总结
mongodb与mysql指挥控制
由数据库中的一般传统的关系数据库(database)、表(table)、记录(record)三个层次概念组成。MongoDB是由数据库(database)、集合(collection)、文档对象(document)三个层次组成。MongoDB对于关系型数据库里的表,可是集合中没有列、行和关系概念,这体现了模式自由的特点。
MySQL |
MongoDB |
说明 |
mysqld |
mongod |
server守护进程 |
mysql |
mongo |
client工具 |
mysqldump |
mongodump |
逻辑备份工具 |
mysql |
mongorestore |
逻辑恢复工具 |
db.repairDatabase() |
修复数据库 |
|
mysqldump |
mongoexport |
数据导出工具 |
source |
mongoimport |
数据导入工具 |
grant * privileges on *.* to … |
Db.addUser() Db.auth() |
新建用户并权限 |
show databases |
show dbs |
显示库列表 |
Show tables |
Show collections |
显示表列表 |
Show slave status |
Rs.status |
查询主从状态 |
Create table users(a int, b int) |
db.createCollection("mycoll", {capped:true, size:100000}) 另:可隐式创建表。 |
创建表 |
Create INDEX idxname ON users(name) |
db.users.ensureIndex({name:1}) |
创建索引 |
Create INDEX idxname ON users(name,ts DESC) |
db.users.ensureIndex({name:1,ts:-1}) |
创建索引 |
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 |
db.users.find({'age':{$lt:33}}) |
条件查询 |
select * from users where age>33 and age<=40 |
db.users.find({'age':{$gt:33,$lte:40}}) |
条件查询 |
select * from users where a=1 and b='q' |
db.users.find({a:1,b:'q'}) |
条件查询 |
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 * from users where name like "%Joe%" |
db.users.find({name:/Joe/}) |
模糊查询 |
select * from users where name like "Joe%" |
db.users.find({name:/^Joe/}) |
模糊查询 |
select count(1) from users |
Db.users.count() |
获取表记录数 |
select count(1) from users where age>30 |
db.users.find({age: {'$gt': 30}}).count() |
获取表记录数 |
select DISTINCT last_name from users |
db.users.distinct('last_name') |
去掉反复值 |
select * from users ORDER BY name |
db.users.find().sort({name:-1}) |
排序 |
select * from users ORDER BY name DESC |
db.users.find().sort({name:-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'}) |
删除记录 |
db. users.remove() |
删除全部的记录 |
|
drop database IF EXISTS test; |
use test db.dropDatabase() |
删除数据库 |
drop table IF EXISTS test; |
db.mytable.drop() |
删除表/collection |
db.addUser(‘test’, ’test’) |
加入用户 readOnly-->false |
|
db.addUser(‘test’, ’test’, true) |
加入用户 readOnly-->true |
|
db.addUser("test","test222") |
更改password |
|
db.system.users.remove({user:"test"}) 或者db.removeUser('test') |
删除用户 |
|
use admin |
超级用户 |
|
db.auth(‘test’, ‘test’) |
用户授权 |
|
db.system.users.find() |
查看用户列表 |
|
show users |
查看全部用户 |
|
db.printCollectionStats() |
查看各collection的状态 |
|
db.printReplicationInfo() |
查看主从复制状态 |
|
show profile |
查看profiling |
|
db.copyDatabase('mail_addr','mail_addr_tmp') |
拷贝数据库 |
|
db.users.dataSize() |
查看collection数据的大小 |
|
db. users.totalIndexSize() |
查询索引的大小 |
mongodb语法
MongoDB的优点挺多的,比方多列索引,查询时能够用一些统计函数,支持多条件查询,可是眼下多表查询是不支持的,能够想办法通过数据冗余来解决多表查询的问题。
MongoDB对数据的操作非常丰富。以下做一些举例说明。内容大部分来自官方文档,另外有部分为自己理解。
查询colls全部数据
db.colls.find() //select * from colls
通过指定条件查询
db.colls.find({‘last_name’: ‘Smith’});//select * from colls where last_name=’Smith’
指定多条件查询
db.colls.find( { x : 3, y : “foo” } );//select * from colls where x=3 and y=’foo’
指定条件范围查询
db.colls.find({j: {$ne: 3}, k: {$gt: 10} });//select * from colls where j!=3 and k>10
查询不包含某内容
db.colls.find({}, {a:0});//查询除a为0外的全部数据
支持<, <=, >, >=查询。需用符号替代分别为$lt,$lte,$gt,$gte
db.colls.find({ “field” : { $gt: value } } );
db.colls.find({ “field” : { $lt: value } } );
db.colls.find({ “field” : { $gte: value } } );
db.colls.find({ “field” : { $lte: value } } );
也可对某一字段做范围查询
db.colls.find({ “field” : { $gt: value1, $lt: value2 } } );
不等于查询用字符$ne
db.colls.find( { x : { $ne : 3 } } );
in查询用字符$in
db.colls.find( { “field” : { $in : array } } );
db.colls.find({j:{$in: [2,4,6]}});
not in查询用字符$nin
db.colls.find({j:{$nin: [2,4,6]}});
取模查询用字符$mod
db.colls.find( { a : { $mod : [ 10 , 1 ] } } )// where a % 10 == 1
$all查询
db.colls.find( { a: { $all: [ 2, 3 ] } } );//指定a满足数组中随意值时
$size查询
db.colls.find( { a : { $size: 1 } } );//对对象的数量查询,此查询查询a的子对象数目为1的记录
$exists查询
db.colls.find( { a : { $exists : true } } ); // 存在a对象的数据
db.colls.find( { a : { $exists : false } } ); // 不存在a对象的数据
$type查询$type值为bsonhttp://bsonspec.org/数 据的类型值
db.colls.find( { a : { $type : 2 } } ); // 匹配a为string类型数据
db.colls.find( { a : { $type : 16 } } ); // 匹配a为int类型数据
使用正則表達式匹配
db.colls.find( { name : /acme.*corp/i } );//类似于SQL中like
内嵌对象查询
db.colls.find( { “author.name” : “joe” } );
1.3.3版本号及更高版本号包括$not查询
db.colls.find( { name : { $not : /acme.*corp/i } } );
db.colls.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
sort()排序
db.colls.find().sort( { ts : -1 } );//1为升序2为降序
limit()对限制查询数据返回个数
db.colls.find().limit(10)
skip()跳过某些数据
db.colls.find().skip(10)
snapshot()快照保证没有反复数据返回或对象丢失
count()统计查询对象个数
db.students.find({‘address.state’ : ‘CA’}).count();//效率较高
db.students.find({‘address.state’ : ‘CA’}).toArray().length;//效率非常低
group()对查询结果分组和SQL中group by函数类似
distinct()返回不反复值
DB shell数据操作
shell命令操作语法和JavaScript非常类似。事实上控制台底层的查询语句都是用JavaScript脚本完毕操作的。
Ø 数据库
1、Help查看命令提示
- > help
- > db.help();
- > db.yourColl.help();
- > db.youColl.find().help();
- > rs.help();
2、切换/创建数据库
- > use yourDB;
当创建一个集合(table)的时候会自己主动创建当前数据库
3、查询全部数据库
- > show dbs;
4、删除当前使用数据库
- > db.dropDatabase();
5、从指定主机上克隆数据库
- > db.cloneDatabase(“127.0.0.1”);
将指定机器上的数据库的数据克隆到当前数据库
6、从指定的机器上复制指定数据库数据到某个数据库
- > db.copyDatabase("mydb", "temp", "127.0.0.1");
将本机的mydb的数据拷贝到temp数据库中
7、修复当前数据库
- > db.repairDatabase();
8、查看当前使用的数据库
- > db.getName();
- > db;
db和getName方法是一样的效果,都能够查询当前使用的数据库
9、显示当前db状态
- > db.stats();
10、当前db版本号
- > db.version();
11、查看当前db的链接机器地址
- > db.getMongo();
Ø Collection聚集集合
1、创建一个聚集集合(table)
- > db.createCollection(“collName”, {size: 20, capped: 5, max: 100});
2、得到指定名称的聚集集合(table)
- > db.getCollection("account");
3、得到当前db的全部聚集集合
- > db.getCollectionNames();
4、显示当前db全部聚集索引的状态
- > db.printCollectionStats();
Ø 用户相关
1、加入一个用户
- > db.addUser("name");
- > db.addUser("userName", "pwd123", true);
加入用户、设置password、是否仅仅读
2、数据库认证、安全模式
- > db.auth("userName", "123123");
3、显示当前全部用户
- > show users;
4、删除用户
- > db.removeUser("userName");
Ø 其它
1、查询之前的错误信息
- > db.getPrevError();
2、清除错误记录
- > db.resetError();
三、Collection聚集集合操作
Ø 查看聚集集合基本信息
1、查看帮助
- > db.yourColl.help();
2、查询当前集合的数据条数
- > db.yourColl.count();
3、查看数据空间大小
- > db.userInfo.dataSize();
4、得到当前聚集集合所在的db
- > db.userInfo.getDB();
5、得到当前聚集的状态
> db.userInfo.stats();
6、得到聚集集合总大小
> db.userInfo.totalSize();
7、聚集集合储存空间大小
> db.userInfo.storageSize();
8、Shard版本号信息
> db.userInfo.getShardVersion()
9、聚集集合重命名
> db.userInfo.renameCollection("users");
将userInfo重命名为users
10、删除当前聚集集合
> db.userInfo.drop();
Ø 聚集集合查询
1、查询全部记录
> db.userInfo.find();
相当于:select * from userInfo;
默认每页显示20条记录,当显示不下的情况下,能够用it迭代命令查询下一页数据。
注意:键入it命令不能带“;”
可是你能够设置每页显示数据的大小,用DBQuery.shellBatchSize = 50;这样每页就显示50条记录了。
2、查询去掉后的当前聚集集合中的某列的反复数据
> db.userInfo.distinct("name");
会过滤掉name中的同样数据
相当于:select distict name from userInfo;
3、查询age = 22的记录
> db.userInfo.find({"age": 22});
相当于:select * from userInfo where age = 22;
4、查询age > 22的记录
> db.userInfo.find({age: {$gt: 22}});
相当于:select * from userInfo where age > 22;
5、查询age < 22的记录
> db.userInfo.find({age: {$lt: 22}});
相当于:select * from userInfo where age < 22;
6、查询age >= 25的记录
> db.userInfo.find({age: {$gte: 25}});
相当于:select * from userInfo where age >= 25;
7、查询age <= 25的记录
> db.userInfo.find({age: {$lte: 25}});
8、查询age >= 23 而且 age <= 26
> db.userInfo.find({age: {$gte: 23, $lte: 26}});
9、查询name中包括 mongo的数据
> db.userInfo.find({name: /mongo/});
相当于:select * from userInfo where name like ‘%mongo%’;
10、查询name中以mongo开头的
> db.userInfo.find({name: /^mongo/});
select * from userInfo where name like ‘mongo%’;
11、查询指定列name、age数据
> db.userInfo.find({}, {name: 1, age: 1});
相当于:select name, age from userInfo;
当然name也能够用true或false,当用ture的情况下河name:1效果一样。假设用false就是排除name。显示name以外的列信息。
12、查询指定列name、age数据, age > 25
> db.userInfo.find({age: {$gt: 25}}, {name: 1, age: 1});
相当于:select name, age from userInfo where age > 25;
13、依照年龄排序
升序:
> db.userInfo.find().sort({age: 1});
降序:
> db.userInfo.find().sort({age: -1});
14、查询name = zhangsan, age = 22的数据
> db.userInfo.find({name: 'zhangsan', age: 22});
相当于:select * from userInfo where name = ‘zhangsan’ and age = ‘22’;
15、查询前5条数据
> db.userInfo.find().limit(5);
相当于:select top 5 * from userInfo;
16、查询10条以后的数据
> db.userInfo.find().skip(10);
相当于:select * from userInfo where id not in ( select top 10 * from userInfo );
17、查询在5-10之间的数据
> db.userInfo.find().limit(10).skip(5);
可用于分页,limit是pageSize。skip是第几页*pageSize
18、or与 查询
> db.userInfo.find({$or: [{age: 22}, {age: 25}]});
相当于:select * from userInfo where age = 22 or age = 25;
19、查询第一条数据
> db.userInfo.findOne();
相当于:select top 1 * from userInfo;
> db.userInfo.find().limit(1);
20、查询某个结果集的记录条数
> db.userInfo.find({age: {$gte: 25}}).count();
相当于:select count(*) from userInfo where age >= 20;
21、依照某列进行排序
> db.userInfo.find({sex: {$exists: true}}).count();
相当于:select count(sex) from userInfo;
Ø 索引
1、创建索引
> db.userInfo.ensureIndex({name: 1});
> db.userInfo.ensureIndex({name: 1, ts: -1});
2、查询当前聚集集合全部索引
> db.userInfo.getIndexes();
3、查看总索引记录大小
> db.userInfo.totalIndexSize();
4、读取当前集合的全部index信息
> db.users.reIndex();
5、删除指定索引
> db.users.dropIndex("name_1");
6、删除全部索引索引
> db.users.dropIndexes();
Ø 改动、加入、删除集合数据
1、加入
> db.users.save({name: ‘zhangsan’, age: 25, sex: true});
加入的数据的数据列。没有固定,依据加入的数据为准
2、改动
> db.users.update({age: 25}, {$set: {name: 'changeName'}}, false, true);
相当于:update users set name = ‘changeName’ where age = 25;
> db.users.update({name: 'Lisi'}, {$inc: {age: 50}}, false, true);
相当于:update users set age = age + 50 where name = ‘Lisi’;
> db.users.update({name: 'Lisi'}, {$inc: {age: 50}, $set: {name: 'hoho'}}, false, true);
相当于:update users set age = age + 50, name = ‘hoho’ where name = ‘Lisi’;
3、删除
> db.users.remove({age: 132});
4、查询改动删除
- > db.users.findAndModify({
- ... query: {age: {$gte: 25}},
- ... sort: {age: -1},
- ... update: {$set: {name: 'a2'}, $inc: {age: 2}},
- ... remove: true
- ... });
- > db.runCommand({ findandmodify : "users",
- ... query: {age: {$gte: 25}},
- ... sort: {age: -1},
- ... update: {$set: {name: 'a2'}, $inc: {age: 2}},
- ... remove: true
- ... });
update 或 remove 当中一个是必须的參数; 其它參数可选。
參数 |
具体解释 |
默认值 |
query |
查询过滤条件 |
{} |
sort |
假设多个文档符合查询过滤条件,将以该參数指定的排列方式选择出排在首位的对象,该对象将被操作 |
{} |
remove |
若为true,被选中对象将在返回前被删除 |
N/A |
update |
一个 改动器对象 |
N/A |
new |
若为true,将返回改动后的对象而不是原始对象。 在删除操作中。该參数被忽略。 |
false |
fields |
參见Retrieving a Subset of Fields (1.5.0+) |
All fields |
upsert |
创建新对象若查询结果为空。 演示样例 (1.5.4+) |
false |
1、简单Hello World
- > print("Hello World!");
这样的写法调用了print函数,和直接写入"Hello World!"的效果是一样的;
2、将一个对象转换成json
- > tojson(new Object());
- > tojson(new Object('a'));
3、循环加入数据
- > for (var i = 0; i < 30; i++) {
- ... db.users.save({name: "u_" + i, age: 22 + i, sex: i % 2});
- ... };
这样就循环加入了30条数据,相同也能够省略括号的写法
- > for (var i = 0; i < 30; i++) db.users.save({name: "u_" + i, age: 22 + i, sex: i % 2});
也是能够的,当你用db.users.find()查询的时候,显示多条数据而无法一页显示的情况下。能够用it查看下一页的信息;
4、find 游标查询
- >var cursor = db.users.find();
- > while (cursor.hasNext()) {
- ... printjson(cursor.next());
- ... }
这样就查询全部的users信息。相同能够这样写
- >var cursor = db.users.find();
- >while (cursor.hasNext()) { printjson(cursor.next); }
相同能够省略{}号
5、forEach迭代循环
- >db.users.find().forEach(printjson);
forEach中必须传递一个函数来处理每条迭代的数据信息
6、将find游标当数组处理
- > var cursor = db.users.find();
- > cursor[4];
取得下标索引为4的那条数据
既然能够当做数组处理,那么就能够获得它的长度:cursor.length();或者cursor.count();
那样我们也能够用循环显示数据
- > for (var i = 0, len = c.length(); i < len; i++) printjson(c[i]);
7、将find游标转换成数组
- > var arr = db.users.find().toArray();
- > printjson(arr[2]);
用toArray方法将其转换为数组
8、定制我们自己的查询结果
仅仅显示age <= 28的而且仅仅显示age这列数据
- > db.users.find({age: {$lte: 28}}, {age: 1}).forEach(printjson);
- > db.users.find({age: {$lte: 28}}, {age: true}).forEach(printjson);
排除age的列
- > db.users.find({age: {$lte: 28}}, {age: false}).forEach(printjson);
9、forEach传递函数显示信息
- > db.things.find({x:4}).forEach(function(x) {print(tojson(x));});
上面介绍过forEach须要传递一个函数,函数会接受一个參数。就是当前循环的对象,然后在函数体重处理传入的參数信息。
那么关于mongodb的shell操作的解说就先到这了,基本涵盖了mongodb最为经常使用的操作方法。那么下一节我们会讲据说使用java如何推动mongodb,所谓CRUD。
版权声明:本文博客原创文章,博客,未经同意,不得转载。
Mongodb语法总结的更多相关文章
- mongodb语法备份(转)
mongodb语法 MongoDB的好处挺多的,比如多列索引,查询时可以用一些统计函数,支持多条件查询,但是目前多表查询是不支持的,可以想办法通过数据冗余来解决多表查询的问题. 查询colls所有数据 ...
- MongoDB 语法(转)
Mongod.exe 是用来连接到mongo数据库服务器的,即服务器端. Mongo.exe 是用来启动MongoDB shell的,即客户端. 其他文件: mongodump 逻辑备份工具. mon ...
- MongoDB语法与现有关系型数据库SQL语法比较
MongoDB语法 MySql语法 db.test.find({'name':'foobar'}) <==> select ...
- Mongodb 语法,update,insert,delete,find
---恢复内容开始--- db.Users.update({OrganizationCode:"Global"},{$set:{OrganizationCode:"Fre ...
- MongoDB 语法使用小结
MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的 他支持的数据结构非常松散,是类似json的bjson格式,因此可以存储比较复杂的数据 ...
- mongodb 语法小结
数据库 一个mongodb中可以建立多个数据库. MongoDB的默认数据库为"db",该数据库存储在data目录中. MongoDB的单个实例可以容纳多个独立的数据库,每一个都有 ...
- MongoDB命令及SQL语法对比
mongodb与mysql命令对比 传统的关系数据库一般由数据库(database).表(table).记录(record)三个层次概念组成,MongoDB是由数据库(database).集合(col ...
- MongoDB(五)mongo语法和mysql语法对比学习
我们总是在对比中看到自己的优点和缺点,对于mongodb来说也是一样,对比学习让我们尽快的掌握关于mongodb的基础知识. mongodb与MySQL命令对比 关系型数据库一般是由数据库(datab ...
- mongoDB的常用语法
安装: 到mongodb官网下载安装包或者压缩包:https://www.mongodb.com/download-center?jmp=nav 1.如果是msi包的话则点击按步骤安装,如果是压缩包的 ...
随机推荐
- 【转】.net IL 指令解释速查
名称 说明 Add 将两个值相加并将结果推送到计算堆栈上. Add.Ovf 将两个整数相加,执行溢出检查,并且将结果推送到计算堆栈上. Add.Ovf.Un 将两个无符号整数值相加,执行溢出检查,并且 ...
- BZOJ 1038 ZJOI2008 瞭望塔 半平面交
题目大意及模拟退火题解:见 http://blog.csdn.net/popoqqq/article/details/39340759 这次用半平面交写了一遍--求出半平面交之后.枚举原图和半平面交的 ...
- 深入浅出KnockoutJS
深入浅出KnockoutJS 写在前面,本文资料大多来源网上,属于自己的学习笔记整理. 其中主要内容来自learn.knockoutjs.com,源码解析部分资料来自司徒正美博文<knockou ...
- NYOJ 47 河问题
时间限制:1000 ms | 内存限制:65535 KB 难度:5 描写叙述 在漆黑的夜里,N位旅行者来到了一座狭窄并且没有护栏的桥边.假设不借助手电筒的话,大家是不管怎样也不敢过桥去的.不幸的是 ...
- (23)unity4.6学习Ugui中国文档-------非官方Demo1
大家好,我是广东太阳. 转载请注明出处:http://write.blog.csdn.net/postedit/38922399 更全的内容请看我的游戏蛮牛地址:http://www.unitym ...
- net Mvc模块化开发
Asp.net Mvc模块化开发之“部分版本部分模块更新(上线)” 项目开发从来就不是一个简单的问题.更难的问题是维护其他人开发的项目,并且要修改bug.如果原系统有重大问题还需要重构. 怎么重构系统 ...
- Android下的单元測试
android下的单元測试 在AndroidManifest.xml文件里配置下面信息: 在manifest节点下加入: <!-- 指定測试信息和要測试的包 --> <instrum ...
- MATLAB导入数据importdata功能
用load函数导入mat文件大家都会.可是今天我拿到一个数据,文件后缀名竟然是'.data'.该怎么读呢? 我仅仅好用matlab界面Workspace区域的"import data&quo ...
- php文件操作基本使用方法
<?php /* $fp=fopen("tmp.html","r"); $str=fread($fp,filesize("tmp.html&qu ...
- mongodb笔记2
成功启动MongoDB后,再打开一个命令行窗口输入mongo,就可以进行数据库的一些操作. 输入help可以看到基本操作命令: show dbs:显示数据库列表 show collections:显示 ...