PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

Mongodb语法总结

原创
2016-06-07 15:58:15 756浏览

MySQL MongoDB 说明 mysqld mongod 服务器守护进程 mysql mongo 客户端工具 mysqldump mongodump 逻辑备份工具 mysql mongorestore 逻辑恢复工具 db.repairDatabase() 修复数据库 mysqldump mongoexport 数据导出工具 source mongoimport 数据导入工具 grant

  1. MySQL
  1. MongoDB
  1. 说明
  1. mysqld
  1. mongod
  1. 服务器守护进程
  1. mysql
  1. mongo
  1. 客户端工具
  1. mysqldump
  1. mongodump
  1. 逻辑备份工具
  1. mysql
  1. mongorestore
  1. 逻辑恢复工具
  1. db.repairDatabase()
  1. 修复数据库
  1. mysqldump
  1. mongoexport
  1. 数据导出工具
  1. source
  1. mongoimport
  1. 数据导入工具
  1. grant * privileges on *.* to …
  1. Db.addUser()
  2. Db.auth()
  1. 新建用户并权限
  1. show databases
  1. show dbs
  1. 显示库列表
  1. Show tables
  1. Show collections
  1. 显示表列表
  1. Show slave status
  1. Rs.status
  1. 查询主从状态
  1. Create table users(a int, b int)
  1. db.createCollection("mycoll", {capped:true,
  2. size:100000}) 另:可隐式创建表。
  1. 创建表
  1. Create INDEX idxname ON users(name)
  1. db.users.ensureIndex({name:1})
  1. 创建索引
  1. Create INDEX idxname ON users(name,ts DESC)
  1. db.users.ensureIndex({name:1,ts:-1})
  1. 创建索引
  1. Insert into users values(1, 1)
  1. db.users.insert({a:1, b:1})
  1. 插入记录
  1. Select a, b from users
  1. db.users.find({},{a:1, b:1})
  1. 查询表
  1. Select * from users
  1. db.users.find()
  1. 查询表
  1. Select * from users where age=33
  1. db.users.find({age:33})
  1. 条件查询
  1. Select a, b from users where age=33
  1. db.users.find({age:33},{a:1, b:1})
  1. 条件查询
  1. select * from users where age
  1. db.users.find({'age':{$lt:33}})
  1. 条件查询
  1. select * from users where age>33 and age
  1. db.users.find({'age':{$gt:33,$lte:40}})
  1. 条件查询
  1. select * from users where a=1 and b='q'
  1. db.users.find({a:1,b:'q'})
  1. 条件查询
  1. select * from users where a=1 or b=2
  1. db.users.find( { $or : [ { a : 1 } , { b : 2 } ] } )
  1. 条件查询
  1. select * from users limit 1
  1. db.users.findOne()
  1. 条件查询
  1. select * from users where name like "%Joe%"
  1. db.users.find({name:/Joe/})
  1. 模糊查询
  1. select * from users where name like "Joe%"
  1. db.users.find({name:/^Joe/})
  1. 模糊查询
  1. select count(1) from users
  1. Db.users.count()
  1. 获取表记录数
  1. select count(1) from users where age>30
  1. db.users.find({age: {'$gt': 30}}).count()
  1. 获取表记录数
  1. select DISTINCT last_name from users
  1. db.users.distinct('last_name')
  1. 去掉重复值
  1. select * from users ORDER BY name
  1. db.users.find().sort({name:-1})
  1. 排序
  1. select * from users ORDER BY name DESC
  1. db.users.find().sort({name:-1})
  1. 排序
  1. EXPLAIN select * from users where z=3
  1. db.users.find({z:3}).explain()
  1. 获取存储路径
  1. update users set a=1 where b='q'
  1. db.users.update({b:'q'}, {$set:{a:1}}, false, true)
  1. 更新记录
  1. update users set a=a+2 where b='q'
  1. db.users.update({b:'q'}, {$inc:{a:2}}, false, true)
  1. 更新记录
  1. delete from users where z="abc"
  1. db.users.remove({z:'abc'})
  1. 删除记录
  1. db. users.remove()
  1. 删除所有的记录
  1. drop database IF EXISTS test;
  1. use test
  2. db.dropDatabase()
  1. 删除数据库
  1. drop table IF EXISTS test;
  1. db.mytable.drop()
  1. 删除表/collection
  1. db.addUser(‘test’, ’test’)
  1. 添加用户
  2. readOnly-->false
  1. db.addUser(‘test’, ’test’, true)
  1. 添加用户
  2. readOnly-->true
  1. db.addUser("test","test222")
  1. 更改密码
  1. db.system.users.remove({user:"test"})
  2. 或者db.removeUser('test')
  1. 删除用户
  1. use admin
  1. 超级用户
  1. db.auth(‘test’, ‘test’)
  1. 用户授权
  1. db.system.users.find()
  1. 查看用户列表
  1. show users
  1. 查看所有用户
  1. db.printCollectionStats()
  1. 查看各collection的状态
  1. db.printReplicationInfo()
  1. 查看主从复制状态
  1. show profile
  1. 查看profiling
  1. db.copyDatabase('mail_addr','mail_addr_tmp')
  1. 拷贝数据库
  1. db.users.dataSize()
  1. 查看collection数据的大小
  1. db. users.totalIndexSize()
  1. 查询索引的大小
mongodb与mysql命令对比
传统的关系数据库一般由数据库(database)、表(table)、记录(record)三个层次概念组成,MongoDB是由数据库(database)、集合(collection)、文档对象(document)三个层次组成。MongoDB对于关系型数据库里的表,但是集合中没有列、行和关系概念,这体现了模式自由的特点。
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 plaincopy
> help
> db.help();
> db.yourColl.help();
> db.youColl.find().help();
> rs.help();

2、切换/创建数据库

[html] view plaincopy
> use yourDB;

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

3、查询所有数据库

[html] view plaincopy
> show dbs;

4、删除当前使用数据库

[html] view plaincopy
> db.dropDatabase();

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

[html] view plaincopy
> db.cloneDatabase(“127.0.0.1”);

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

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

[html] view plaincopy
> db.copyDatabase("mydb", "temp", "127.0.0.1");

将本机的mydb的数据复制到temp数据库中

7、修复当前数据库

[html] view plaincopy
> db.repairDatabase();

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

[html] view plaincopy
> db.getName();
> db;

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

9、显示当前db状态

[html] view plaincopy
> db.stats();

10、当前db版本

[html] view plaincopy
> db.version();

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

[html] view plaincopy
> db.getMongo();

? Collection聚集集合

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

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

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

[html] view plaincopy
> db.getCollection("account");

3、得到当前db的所有聚集集合

[html] view plaincopy
> db.getCollectionNames();

4、显示当前db所有聚集索引的状态

[html] view plaincopy
> db.printCollectionStats();

? 用户相关

1、添加一个用户

[html] view plaincopy
> db.addUser("name");
> db.addUser("userName", "pwd123", true);

添加用户、设置密码、是否只读

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

[html] view plaincopy
> db.auth("userName", "123123");

3、显示当前所有用户

[html] view plaincopy
> show users;

4、删除用户

[html] view plaincopy
> db.removeUser("userName");

? 其他

1、查询之前的错误信息

[html] view plaincopy
> db.getPrevError();

2、清除错误记录

[html] view plaincopy
> db.resetError();

三、Collection聚集集合操作

? 查看聚集集合基本信息

1、查看帮助

[html] view plaincopy
> db.yourColl.help();

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

[html] view plaincopy
> db.yourColl.count();

3、查看数据空间大小

[html] view plaincopy
> db.userInfo.dataSize();

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

[html] view plaincopy
> 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

> db.userInfo.find({age: {$lt: 22}});

相当于:select * from userInfo where age

6、查询age >= 25的记录

> db.userInfo.find({age: {$gte: 25}});

相当于:select * from userInfo where age >= 25;

7、查询age

> db.userInfo.find({age: {$lte: 25}});

8、查询age >= 23 并且 age

> 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 plaincopy
> 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

[html] view plaincopy
> print("Hello World!");

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

2、将一个对象转换成json

[html] view plaincopy
> tojson(new Object());
> tojson(new Object('a'));

3、循环添加数据

[html] view plaincopy
> for (var i = 0; i ... db.users.save({name: "u_" + i, age: 22 + i, sex: i % 2});
... };

这样就循环添加了30条数据,同样也可以省略括号的写法

[html] view plaincopy
> for (var i = 0; i 也是可以的,当你用db.users.find()查询的时候,显示多条数据而无法一页显示的情况下,可以用it查看下一页的信息;

4、find 游标查询

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

这样就查询所有的users信息,同样可以这样写

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

同样可以省略{}号

5、forEach迭代循环

[html] view plaincopy
>db.users.find().forEach(printjson);

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

6、将find游标当数组处理

[html] view plaincopy
> var cursor = db.users.find();
> cursor[4];

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

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

那样我们也可以用循环显示数据

[html] view plaincopy
> for (var i = 0, len = c.length(); i 7、将find游标转换成数组 [html] view plaincopy
> var arr = db.users.find().toArray();
> printjson(arr[2]);

用toArray方法将其转换为数组

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

只显示age [html] view plaincopy
> db.users.find({age: {$lte: 28}}, {age: 1}).forEach(printjson);
> db.users.find({age: {$lte: 28}}, {age: true}).forEach(printjson);

排除age的列

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

9、forEach传递函数显示信息

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

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

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

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。