Mongodb语法总结

Mongodb语法总结

大家好,又见面了,我是全栈君,今天给大家准备了Idea注册码。

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查看命令提示

[html] 
view plain
copy
  1. > help  
  2. > db.help();  
  3. > db.yourColl.help();  
  4. > db.youColl.find().help();  
  5. > rs.help();  

2、切换/创建数据库

[html] 
view plain
copy
  1. > use yourDB;  

当创建一个集合(table)的时候会自己主动创建当前数据库

3、查询全部数据库

[html] 
view plain
copy
  1. > show dbs;  

4、删除当前使用数据库

[html] 
view plain
copy
  1. > db.dropDatabase();  

5、从指定主机上克隆数据库

[html] 
view plain
copy
  1. > db.cloneDatabase(“127.0.0.1”);  

将指定机器上的数据库的数据克隆到当前数据库

6、从指定的机器上复制指定数据库数据到某个数据库

[html] 
view plain
copy
  1. > db.copyDatabase(“mydb”, “temp”, “127.0.0.1”);  

将本机的mydb的数据拷贝到temp数据库中

7、修复当前数据库

[html] 
view plain
copy
  1. > db.repairDatabase();  

8、查看当前使用的数据库

[html] 
view plain
copy
  1. > db.getName();  
  2. > db;  

db和getName方法是一样的效果,都能够查询当前使用的数据库

9、显示当前db状态

[html] 
view plain
copy
  1. > db.stats();  

10、当前db版本号

[html] 
view plain
copy
  1. > db.version();  

11、查看当前db的链接机器地址

[html] 
view plain
copy
  1. > db.getMongo();  

Ø Collection聚集集合

1、创建一个聚集集合(table)

[html] 
view plain
copy
  1. > db.createCollection(“collName”, {size: 20, capped: 5, max: 100});  

2、得到指定名称的聚集集合(table)

[html] 
view plain
copy
  1. > db.getCollection(“account”);  

3、得到当前db的全部聚集集合

[html] 
view plain
copy
  1. > db.getCollectionNames();  

4、显示当前db全部聚集索引的状态

[html] 
view plain
copy
  1. > db.printCollectionStats();  

Ø 用户相关

1、加入一个用户

[html] 
view plain
copy
  1. > db.addUser(“name”);  
  2. > db.addUser(“userName”, “pwd123”, true);  

加入用户、设置password、是否仅仅读

2、数据库认证、安全模式

[html] 
view plain
copy
  1. > db.auth(“userName”, “123123”);  

3、显示当前全部用户

[html] 
view plain
copy
  1. > show users;  

4、删除用户

[html] 
view plain
copy
  1. > db.removeUser(“userName”);  

Ø 其它

1、查询之前的错误信息

[html] 
view plain
copy
  1. > db.getPrevError();  

2、清除错误记录

[html] 
view plain
copy
  1. > db.resetError();   

三、Collection聚集集合操作

Ø 查看聚集集合基本信息

1、查看帮助

[html] 
view plain
copy
  1. > db.yourColl.help();  

2、查询当前集合的数据条数

[html] 
view plain
copy
  1. > db.yourColl.count();  

3、查看数据空间大小

[html] 
view plain
copy
  1. > db.userInfo.dataSize();  

4、得到当前聚集集合所在的db

[html] 
view plain
copy
  1. > 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、查询改动删除

[html] 
view plain
copy
  1. > db.users.findAndModify({  
  2. … query: {age: {$gte: 25}},   
  3. … sort: {age: -1},   
  4. … update: {$set: {name: ‘a2’}, $inc: {age: 2}},  
  5. … remove: true  
  6. … });  
  7.    
  8. > db.runCommand({ findandmodify : “users”,   
  9. … query: {age: {$gte: 25}},   
  10. … sort: {age: -1},   
  11. … update: {$set: {name: ‘a2’}, $inc: {age: 2}},  
  12. … remove: true  
  13. … });  

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

[html] 
view plain
copy
  1. > print(“Hello World!”);  

这样的写法调用了print函数,和直接写入”Hello World!”的效果是一样的;

2、将一个对象转换成json

[html] 
view plain
copy
  1. > tojson(new Object());  
  2. > tojson(new Object(‘a’));  

3、循环加入数据

[html] 
view plain
copy
  1. > for (var i = 0; i < 30; i++) {  
  2. … db.users.save({name: “u_” + i, age: 22 + i, sex: i % 2});  
  3. … };  

这样就循环加入了30条数据,相同也能够省略括号的写法

[html] 
view plain
copy
  1. > 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 游标查询

[html] 
view plain
copy
  1. >var cursor = db.users.find();  
  2. > while (cursor.hasNext()) {   
  3. … printjson(cursor.next());   
  4. … }  

这样就查询全部的users信息。相同能够这样写

[html] 
view plain
copy
  1. >var cursor = db.users.find();  
  2. >while (cursor.hasNext()) { printjson(cursor.next); }  

相同能够省略{}号

5、forEach迭代循环

[html] 
view plain
copy
  1. >db.users.find().forEach(printjson);  

forEach中必须传递一个函数来处理每条迭代的数据信息

6、将find游标当数组处理

[html] 
view plain
copy
  1. > var cursor = db.users.find();  
  2. > cursor[4];  

取得下标索引为4的那条数据

既然能够当做数组处理,那么就能够获得它的长度:cursor.length();或者cursor.count();

那样我们也能够用循环显示数据

[html] 
view plain
copy
  1. > for (var i = 0len = c.length(); i < len; i++) printjson(c[i]);  

7、将find游标转换成数组

[html] 
view plain
copy
  1. > var arr = db.users.find().toArray();  
  2. > printjson(arr[2]);  

用toArray方法将其转换为数组

8、定制我们自己的查询结果

仅仅显示age <= 28的而且仅仅显示age这列数据

[html] 
view plain
copy
  1. > db.users.find({age: {$lte: 28}}, {age: 1}).forEach(printjson);  
  2. > db.users.find({age: {$lte: 28}}, {age: true}).forEach(printjson);  

排除age的列

[html] 
view plain
copy
  1. > db.users.find({age: {$lte: 28}}, {age: false}).forEach(printjson);  

9、forEach传递函数显示信息

[html] 
view plain
copy
  1. > db.things.find({x:4}).forEach(function(x) {print(tojson(x));});  

上面介绍过forEach须要传递一个函数,函数会接受一个參数。就是当前循环的对象,然后在函数体重处理传入的參数信息。

 

那么关于mongodb的shell操作的解说就先到这了,基本涵盖了mongodb最为经常使用的操作方法。那么下一节我们会讲据说使用java如何推动mongodb,所谓CRUD。

版权声明:本文博客原创文章,博客,未经同意,不得转载。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/117181.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号