mongdb安装使用

一、准备工作

1.首先去官网上下载程序,我用的是1.4.3版本

 http://downloads.mongodb.org/win32/mongodb-win32-i386-1.4.3.zip

也可以通过这里下载:http://download.csdn.net/detail/shiyuezhong/4553412

我解压后放在E盘根目录下。

2.创建一个DB文件夹,C:\data\db 然后运行解压下来的bin下面的mongod.exe,即 E:\mongodb\bin\mongod.exe  就可以启动服务,默认端口27017;如果你的data\db文件建立在其他盘,比如E盘根目录下,则要打开cmd执行

E:\mongodb\bin\mongod.exe --dbpath=E:\data\db 否则mongod.exe运行不成功。

3.现在执行E:\mongodb\bin\下的mongo.exe  OK,连接成功。进行简单测试:

> db      //显示当前使用的数据库

test

> db.foo.insert({id: 2012, userName: 'syz', age: 24, email:  "shiyuezhong@zrar.com"}); //添加数据

> db.foo.find();     //查询数据

"_id" : ObjectId("5012a9a33208000000007581"), "id" : 2012"userName" : "syz",

"age" : 24, "email" : "shiyuezhong@zrar.com"}

二、DB shell数据操作

shell命令操作语法和JavaScript很类似,其实控制台底层的查询语句都是用JavaScript脚本完成操作的。

Ø 数据库

1Help查看命令提示

help

db.help();

db.yourColl.help();     //yourColl是指你的集合名  下同

db.yourColl.find().help();

rs.help();

 

2、切换/创建数据库

>use syz;  //syz是你自己随便取的数据库名

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

 

3、查询所有数据库

show dbs;   //当上面syz数据库里面还没有数据的时候是不会显示的

 

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;

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

 

9、显示当前db状态

db.stats();

 

10、当前db版本

db.version();

 

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

db.getMongo();

Ø Collection聚集集合

数据被分组到若干集合,这些集合称作聚集(collections). 在数据库里每个聚集有一个唯一的名字,可以包含无限个文档聚集是RDBMS(关系型数据库管理系统)中表的同义词,区别是聚集不需要进行模式定义.  

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

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

 

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();    //userInfo也是指你的集合名  下同

 

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

db.userInfo.getDB();

 

5、得到当前聚集的状态

db.userInfo.stats();

 

6、得到聚集集合总大小

db.userInfo.totalSize();

 

7、聚集集合储存空间大小

db.userInfo.storageSize();

 

8Shard版本信息

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的记录    查询age=22的记录

db.userInfo.find({"age": 22});

//age加双引号、单引号都可,也可以不加,我为了方便,统一双引号

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

db.userInfo.find({"age":{$ne:20}})    //查询年龄不等于20的记录

$ne是不等于的意思

db.userInfo.find({"age":{$in:[20,40]}});  //查询age2040的记录

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、查询指定列nameage数据

db.userInfo.find({}, {name: 1, age: 1});

相当于select name, age from userInfo;

当然name也可以用truefalse,当用ture的情况下name:1效果一样,如果用false就是排除name,显示name以外的列信息。

12、查询指定列nameage数据, 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

);

//从第一条开始就是db.userInfo.find().skip(0);

 

17、查询在5-10之间的数据

db.userInfo.find().limit(10).skip(5);

可用于分页 

18or与 查询   //?我试了一下,貌似查不出来

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();  

//.count()不能跟在findOne()后面

相当于: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.userInfo.reIndex();

5、删除指定索引

db.userInfo.dropIndex("name_1");

 

6、删除所有索引索引

db.userInfo.dropIndexes();

Ø 修改、添加、删除集合数据

1、添加

db.userInfo.save({name: shiyuezhong, age: 25, sex: true});

添加的数据的数据列,没有固定,根据添加的数据为准,即字段随便取也不会出错

2、修改

db.userInfo.update({age: 25}, {$set: {name: 'changeName'}});

相当于:update userInfo set name = changeName’ where age = 25;

如果age字段不是整型的话则不会更新,string的话用 age"age" double的话用 age25.0

db.userInfo.update({age: 25}, {name: 'changeName'});//这样会把这个age=25document替换为{name: 'changeName'}

3、删除

db.userInfo.remove({age: 132});

 

4、查询修改删除

db.userInfo.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

$inc
用法:{ $inc : { field : value } }
意思对一个数字字段field增加value,例:
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 16, "test1" : "TESTTEST", "test2" : "OK", "test3" : "TESTTEST", "test4" : "OK", "test5" : "OK" }

> db.test0.update( { "_id" : 15 } , { $inc : { "count" : 1 } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 17, "test1" : "TESTTEST", "test2" : "OK", "test3" : "TESTTEST", "test4" : "OK", "test5" : "OK" }

$set
用法:{ $set : { field : value } }
就是相当于sqlset field = value,全部数据类型都支持$set。例:
> db.test0.update( { "_id" : 15 } , { $set : { "test1" : "testv1","test2" : "testv2","test3" : "testv3","test4" : "testv4" } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : "testv1", "test2" : "testv2", "test3" : "testv3", "test4" : "testv4", "test5" : "OK" }

$unset
用法:{ $unset : { field : 1} }
顾名思义,就是删除字段了。例:
> db.test0.update( { "_id" : 15 } , { $unset : { "test1":1 } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test2" : "testv2", "test3" : "testv3", "test4" : "testv4", "test5" : "OK" }

> db.test0.update( { "_id" : 15 } , { $unset : { "test2": 0 } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test3" : "testv3", "test4" : "testv4", "test5" : "OK" }

> db.test0.update( { "_id" : 15 } , { $unset : { "test3":asdfasf } } );
Fri May 14 16:17:38 JS Error: ReferenceError: asdfasf is not defined (shell):0

> db.test0.update( { "_id" : 15 } , { $unset : { "test3":"test" } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test4" : "testv4", "test5" : "OK" }

没看出field : 1里面的1是干什么用的,反正只要有东西就行。

$push
用法:{ $push : { field : value } }
value追加到field里面去,field一定要是数组类型才行,如果field不存在,会新增一个数组类型加进去。例:

> db.test0.update( { "_id" : 15 } , { $set : { "test1" : ["aaa","bbb"] } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb" ], "test4" : "testv4", "test5" : "OK" }

> db.test0.update( { "_id" : 15 } , { $push : { "test1": "ccc" } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb", "ccc" ], "test4" : "testv4", "test5" : "OK" }

> db.test0.update( { "_id" : 15 } , { $push : { "test2": "ccc" } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb", "ccc" ], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }

> db.test0.update( { "_id" : 15 } , { $push : { "test1": ["ddd","eee"] } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb", "ccc", [ "ddd", "eee" ] ], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }5) 

$pushAll
用法:{ $pushAll : { field : value_array } }
$push,只是一次可以追加多个值到一个数组字段内。例:
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb", "ccc", [ "ddd", "eee" ] ], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }

> db.test0.update( { "_id" : 15 } , { $pushAll : { "test1": ["fff","ggg"] } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb", "ccc", [ "ddd", "eee" ], "fff", "ggg" ], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }

$addToSet
用法:{ $addToSet : { field : value } }
增加一个值到数组内,而且只有当这个值不在数组内才增加。例:
> db.test0.update( { "_id" : 15 } , { $addToSet : { "test1": {$each : ["444","555"] } } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, 

"test1" : ["aaa","bbb","ccc",["ddd","eee"],"fff","ggg","444","555"],"test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK"    

}
> db.test0.update( { "_id" : 15 } , { $addToSet : { "test1": {$each : ["444","555"] } } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, 

"test1" : ["aaa","bbb","ccc",["ddd","eee"],"fff","ggg","444","555"], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" 

}
> db.test0.update( { "_id" : 15 } , { $addToSet : { "test1": ["444","555"] } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, 

 "test1" : ["aaa","bbb","ccc",["ddd","eee"],"fff","ggg","444","555",["444","555"]], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" 

}
> db.test0.update( { "_id" : 15 } , { $addToSet : { "test1": ["444","555"] } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, 

"test1" : ["aaa","bbb","ccc",["ddd","eee"],"fff","ggg",["111","222"],"444","555",["444","555"]], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" 

 }

$pop
删除数组内的一个值
用法:
删除最后一个值:{ $pop : { field : 1 } }删除第一个值:{ $pop : { field : -1 } }
注意,只能删除一个值,也就是说只能用1-1,而不能用2-2来删除两条。mongodb 1.1及以后的版本才可以用,例:
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, 

  "test1" : ["bbb","ccc",["ddd","eee"],"fff","ggg",["111","222"],"444"], 

  "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" 

 }
> db.test0.update( { "_id" : 15 } , { $pop : { "test1": -1 } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, 

  "test1" : ["ccc",["ddd","eee"],"fff","ggg",["111","222"],"444"], 

  "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK"

  }
> db.test0.update( { "_id" : 15 } , { $pop : { "test1": 1 } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, 

"test1" : [ "ccc", [ "ddd", "eee" ], "fff", "ggg", [ "111", "222" ] ], "test2" : [ "ccc" ], "test4" : "testv4",
"test5" : "OK" 

}

$pull
用法:$pull : { field : value } }
从数组field内删除一个等于value值。例:
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "ccc", [ "ddd", "eee" ], "fff", "ggg", [ "111", "222" ] ], "test2" : [ "ccc" ], "test4" : "testv4",
"test5" : "OK" }

> db.test0.update( { "_id" : 15 } , { $pull : { "test1": "ggg" } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "ccc", [ "ddd", "eee" ], "fff", [ "111", "222" ] ], "test2" : [ "ccc" ], "test4" : "testv4", "test5"
: "OK" }

$pullAll
用法:{ $pullAll : { field : value_array } }
$pull,可以一次删除数组内的多个值。例:
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "ccc", [ "ddd", "eee" ], "fff", [ "111", "222" ] ], "test2" : [ "ccc" ], "test4" : "testv4", "test5"
: "OK" }

> db.test0.update( { "_id" : 15 } , { $pullAll : { "test1": [ "ccc" , "fff" ] } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ [ "ddd", "eee" ], [ "111", "222" ] ], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }

操作符
$是他自己的意思,代表按条件找出的数组里面某项他自己。呵呵,比较坳口。看一下官方的例子:
> t.find()
{ "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : "ABC", "comments" : [ { "by" : "joe", "votes" : 3 }, { "by" : "jane", "votes" : 7 } ] }

> t.update( {'comments.by':'joe'}, {$inc:{'comments.$.votes':1}}, false, true )
> t.find()
{ "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : "ABC", "comments" : [ { "by" : "joe", "votes" : 4 }, { "by" : "jane", "votes" : 7 } ] }

需要注意的是,$只会应用找到的第一条数组项,后面的就不管了。还是看例子:
> t.find();
{ "_id" : ObjectId("4b9e4a1fc583fa1c76198319"), "x" : [ 1, 2, 3, 2 ] }
> t.update({x: 2}, {$inc: {"x.$": 1}}, false, true);
> t.find();

还有注意的是$配合$unset使用的时候,会留下一个null的数组项,不过可以用{$pull:{x:null}}删除全部是null的数组项。例:
> t.insert({x: [1,2,3,4,3,2,3,4]})
> t.find()
{ "_id" : ObjectId("4bde2ad3755d00000000710e"), "x" : [ 1, 2, 3, 4, 3, 2, 3, 4 ] }
> t.update({x:3}, {$unset:{"x.$":1}})
> t.find()
{ "_id" : ObjectId("4bde2ad3755d00000000710e"), "x" : [ 1, 2, null, 4, 3, 2, 3, 4 ] }

{ "_id" : ObjectId("4b9e4a1fc583fa1c76198319"), "x" : [ 1, 3, 3, 2 ] }

Ø 语句块操作

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查看下一页的信息;

> it

4find 游标查询

>var cursor = db.users.find();

> while (cursor.hasNext()) {

    printjson(cursor.next());

}

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

var cursor = db.users.find();

while (cursor.hasNext()) { printjson(cursor.next); }

同样可以省略{}

5forEach迭代循环

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

 

9forEach传递函数显示信息

db.things.find({x:4}).forEach(function(x) {print(tojson(x));});

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

四、高级操作部分 

1. 数据据安全

   为了使MongoDB安全生效,必须以--auth参数启动,同时还要在db.system.users文档中增加用户信息

   

   如果在db.system.users中无数据,即使以--auth启动,对于本地的访问也是允许的。

   

   增加一个新的用户:db.addUser("xiaoshi", "bar");

   查询刚才增加的用户:db.system.users.find();

   删除用户:db.removeUser("xiaoshi");

   为了提高查询性能和安全性,也可增加只读用户:db.addUser("xiaoshi", "bar", true);

   

  此时虽然用户已经有了,但是怎么去测试是否生效了呢?先进行认证测试一下,如下:

   db.auth("xiaoshi", "bar");

   如果在服务端打出1则表示认证通过,客户端可以使用了,如果是0表示不通过 

   

   那么在客户端可以通过如下代码进行认证:

   db.authenticate("xiaoshi", "bar".toCharArray());

   由此可知,所有的用户信息是加在数据库上面的,每个库都有自己的用户信息。

   

   如此便可增加安全认证功能了!

2.引用vs 内嵌

在关系型数据库中,我们可以通过外键引用来表达一对多关联,建立中间表来表达多对多关联。在MongoDB中却没有这种机制,我们可以通过对象的引用关系来实现这种关联,也可以把关联的文档内嵌到文档当中。

对于引用这种方式,我们可以通DBRef这个类进行实现。

那么在实际工作当中,我们应该选择哪种存储方式,有如下规则:

1) 顶层对象应该有自己的集合

2) 明细对象应该被嵌入父对象,例如OrderDetailOrder

3) 拥有包含关系的对易用应该被嵌入

4) 对于多对多关联应该使用数据库引用

5) 对于那种稳定的比较小的集合可以在服务器端将其缓存起来从而提高性能

6) 不能去引用一个嵌入的对象,至少目前还无法实现

7) 我们很难去统计嵌入的对象

8) 如果嵌入的对象太多太大会导致单个对象达到他的最大值

9) 记住最后一条:如果遇到性能问题,那么请使用嵌入方式进行存储

3.数据库优化

1)对于排序的字段,请加入索引

现在根据y字段倒序显示:db.users.find().sort({age: -1});,为了提高性能那么需要在字段age上加入索引

db.users.ensureIndex({age:1});这样一来,就可以根据索引排序,而不是直接查绚集合中的所有文档。

2)限制最大记录数:db.users.find().limit(10);

3)只查询所需要的键,而不是所有全查出来:db.users.find({}, {age: 1});

4)统计记录条数利用count()方法:db.users.find().count();

5)强制使用指定索引:db.users.find().hint({y: 1});

4.高级查询

1)利用索引提高查询速度 

首先我们在x字段上建立索引:db.user.ensuerIndex({x : 1});

然后再查询:db.user.find({x:8}, {_id: 0, x: 1}).explain(); 会有如下输出:

{

        "cursor" : "BtreeCursor x_1",

        "nscanned" : 19,

        "nscannedObjects" : 19,

        "n" : 19,

        "millis" : 0,

        "nYields" : 0,

        "nChunkSkips" : 0,

        "isMultiKey" : false,

        "indexOnly" : true,

        ……………………….

}

其中"indexOnly" : true代表着此次查询启用了索引。

一般的查询不会利用索引,除非满足以下条件,

A) 必须列出要返回的字段名,这样才能决定是否需要启用索引

B) 必须显示的指出不显示_id字段{ _id : 0}

2)利用“.”(点号)进行对象间的导航

> db.user.find({}, {“x.y” : 1});

3)查询指定范围的值:db.user.find({y: {$gt : 4, $lt : 10}}); // 4 < y < 10

4)匹配所有$alldb.things.find( { a: { $all: [ 2, 3 ] } } );

5)存在性判断$exists

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

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

6)求余$moddb.things.find( "this.a % 10 == 1"),也可写成如下形式:

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

7)不等于$nedb.things.find( { x : { $ne : 3 } } );

8IN子句$indb.things.find({j:{$in: [2,4,6]}});

9Not In子句$nindb.things.find({j:{$nin: [2,4,6]}});

10OR条件$ordb.foo.find( { $or : [ { a : 1 } , { b : 2 } ] } )

11)利用正则表达式进行复杂匹配

db.customers.find( { name : /acme.*corp/i } );

db.customers.find( { name : { $regex : 'acme.*corp', $options: 'i' } } );

db.customers.find( { name : { $regex : /acme.*corp/i, $nin : ['acmeblahcorp'] } } );

i表示大小写不敏感

12)取反操作$notdb.customers.find( { name : { $not : /acme.*corp/i } } );

13)统计文档数:

nstudents = db.students.find({'address.state' : 'CA'}).count();

不要这样做,这样会导致客户端排序,增加网络传输

nstudents = db.students.find({'address.state' : 'CA'}).toArray().length; // VERY BAD

14)分页查询:n = db.students.find().skip(20).limit(10).count(true);

15)排序sort() db.myCollection.find().sort( { ts : -1 } ); // 按TS降序排列

5.其他

 1)使用web获得mongoDB的信息:http://localhost:28017

 2)数据备份与恢复:

    备份:使用mongodump.exe

       mongodump --db learn --out backup

恢复:使用mongorestore.exe

       mongorestore --collection unicorns backup/learn/unicorns.bson

 3)导入导出数据:

使用mongoexport.exemongoimport.exe

mongoexport --db learn -collection unicorns

mongoexport --db learn -collection unicorns --csv -fields name,weight,vampires


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值