mongo

mongodb与mysql命令对比

传统的关系数据库一般由数据库(database)、表(table)、记录(record)三个层次概念组成,MongoDB是由数据库(database)、集合(collection)、文档对象(document)三个层次组成。MongoDB对于关系型数据库里的表,但是集合中没有列、行和关系概念,这体现了模式自由的特点。 

MySQL

MongoDB

说明

mysqld

mongod

服务器守护进程

mysql

mongo

客户端工具

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")

更改密码

 

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()返回不重复值

---------------------------------------------------------------------------------------

mongodb查询的语法

1 ) . 大于,小于,大于或等于,小于或等于

$gt:大于
$lt:小于
$gte:大于或等于
$lte:小于或等于

例子:

db.collection.find({ "field"
: { $gt: value } } );   // greater than  : field > value

db.collection.find({ "field"
: { $lt: value } } );   // less than  :  field < value

db.collection.find({ "field"
: { $gte: value } } );  // greater than or equal to : field >= value

db.collection.find({ "field"
: { $lte: value } } );  // less than or equal to : field <= value

 

如查询j大于3,小于4:

db.things.find({j : {$lt: 3}});
db.things.find({j : {$gte: 4}});

也可以合并在一条语句内:

db.collection.find({ "field"
 : { $gt: value1, $lt: value2 } } );    // value1 < field < value

2) 不等于 $ne

例子:

db.things.find( { x : { $ne : 3 } } );


3) in 和 not in ($in $nin)

语法:
db.collection.find( { "field"
 : { $in : array } } );

例子:

db.things.find({j:{$in: [2,4,6]}});
db.things.find({j:{$nin: [2,4,6]}});


4) 取模运算$mod

如下面的运算:
db.things.find( "this
.a % 10 == 1"
)

可用$mod代替:

db.things.find( { a : { $mod : [ 10 , 1 ] } } )


5)  $all

$all和$in类似,但是他需要匹配条件内所有的值:

如有一个对象:
{ a: [ 1, 2, 3 ] }

下面这个条件是可以匹配的:

db.things.find( { a: { $all: [ 2, 3 ] } } );

但是下面这个条件就不行了:

db.things.find( { a: { $all: [ 2, 3, 4 ] } } );


6)  $size

$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"] },他只有一个元素:

下面的语句就可以匹配:
db.things.find( { a : { $size: 1 } } );

官网上说不能用来匹配一个范围内的元素,如果想找$size<5之类的,他们建议创建一个字段来保存元素的数量。

You cannot use $size  to find a range of sizes (for example: arrays with more than 1 element). If you need to query for a range, create an extrasize  field that you increment when you add elements.

 

7)$exists

$exists用来判断一个元素是否存在:

如:

db.things.find( { a : { $exists : true
 } } ); // 如果存在

元素

a,就返回

db.things.find( { a : { $exists : false
 } } ); // 如果不存在元素a,就返回


8)  $type

$type  基于 bson  type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。

db.things.find( { a : { $type : 2 } } ); // matches if
 a is a string

db.things.find( { a : { $type : 16 } } ); // matches if
 a is an int

9)正则表达式

mongo支持正则表达式,如:
 

db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写


10)  查询数据内的值

下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
db.things.find( { colors : "red"
 } );

11) $elemMatch

如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:

> t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } ) 
{ "_id"
: ObjectId("4b5783300334000000000aa9"
), 
"x"
: [ { "a"
: 1, "b"
: 3 }, 7, { "b"
: 99 }, { "a"
: 11 } ]
}
 

$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。

注意,上面的语句和下面是不一样的。

> t.find( { "x.a"
 : 1, "x.b"
 : { $gt : 1 } } )

$elemMatch是匹配{ "a"  : 1, "b"  : 3 },而后面一句是匹配{ "b"  : 99 }, { "a"  : 11 } 


12)  查询嵌入对象的值
db.postings.find( { "author.name"
 : "joe"
 } );

注意用法是author.name ,用一个点就行了。更详细的可以看这个链接: dot notation

举个例子:

> db.blog.save({ title : "My First Post"
, author: {name : "Jane"
, id : 1}})

如果我们要查询 authors name 是Jane的, 我们可以这样:

> db.blog.findOne({"author.name"
 : "Jane"
})

如果不用点,那就需要用下面这句才能匹配:

db.blog.findOne({"author"
 : {"name"
 : "Jane"
, "id"
 : 1}})

下面这句:

db.blog.findOne({"author"
 : {"name"
 : "Jane"
}})

是不能匹配的,因为mongodb对于子对象,他是精确匹配。

 

13) 元操作符 $not 取反

如:

db.customers.find( { name : { $not : /acme.*corp/i } } );
db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );

mongodb还有很多函数可以用,如排序,统计等,请参考原文。

mongodb目前没有或(or)操作符,只能用变通的办法代替

--------------------------------------------------------------------------------------------

GUI:

http://download.csdn.net/download/icejoywoo/3822577

此条目发表在article分类目录,贴了标签。将固定链接加入收藏夹。