mongodb学习笔记

1、安装:

mongod -dbpath /home/xxlong/myInstall/mongodb_data

mongod 启动数据库进程

--dbpath 指定数据库的目录

--port 指定数据库的端口,默认是27017

--bind_ip 绑定ip

--directoryperdb 为每个db创建一个独立的子目录

--logpath 指定日志存放目录,默认是控制台

--auth 用安全认证方式启动数据库

--config 指定启动项用文件的路径

--fork 用守护进程的方式启动mongodb

--rest:是打开web监控页面,比如我们这里监听10001端口,则打开http://10.1.49.225:11001/就可以看到这个mongodb数据库进程的信息 

关闭:1ctrl+c 2db.shutdownServer()

2mongodb客户端工具:

mongo 127.0.0.1/27017/admin 不填,默认连接本机test数据库

 

1查看数据库

show dbs

2创建数据库

use xxlong:系统自动创建一个数据库(xxlong)。如果use之后没有创建 任何集合。系统就会删除这个数据库。

3、给定数据库添加集合(student)并添加记录(insert)

db.[documentName].insert({...});

db.student.insert({_id:13,name:'Cat',sex:1,age:23,score:[60,71,81,91,100]});

批量增加:for(var i=1;i<10;i++){

db.student.insert({_id:i,name:'xxl',age:i});

}

insert_id相同的时候会报错,而save则不报错,而是更新

db.student.save({_id:13,name:'xxlong'});

4查看数据库中的所有集合

show collections;

5查看定制文档的数据

db.student.find();查看所有数据

db.student.findOne();查看第一条数据

6更新文档(相当于传统数据库的记录)数据

db.student.update({_id:10},{$set:{age:21}});id10的文档的age改为21$set表示有这个键则修改,没有这个键则增加

db.student.update({age:10},{$set:{sex:1}},true,true),这个true表示查到年龄为10则修改, 查不到则插入,false表示为查到则修改,查不到什么也不做,不写则默认为false(相当于

InsertOrUpdate);这个true表示批量增加(所有年龄为10,修改性别为1,false则不是批量增加,默认为false;

db.student.update({_id:10},{$inc:{age:1}});id10的文档的age自动加1

db.student.update({_id:10},{$unset{age:x}});删除id10的文档的age字段,x为任意数字

db.student.update({_id:13},{$push:{score:[100,101]}});score数组中新增值100,101

如果score键不存在,则新增加这个键,必须为数组

db.student.update({_id:13},{$pop:{score:x}});删除数组中的值,x1删除最后一个,x-1 删除最前的一个

db.student.update({_id:3},{$pull:{course:"computer"}}); 删除数组course中的computer(可以为多个computer值)

db.student.update({_id:3},{$pullAll:{course:["math","english"]}}); 删除数组中多个不同的

db.student.update({_id:10},{$rename:{'age':'AGE'}});修改id10的文档的age字段名


db.student.update({_id:3},{$set:{course:['math','computer']}})

db.student.update({_id:1},{$addToSet:{course:'math'}})结果:math,computer

db.student.update({_id:1},{$addToSet:{course:'english'}})结果:math,computer,english

addToSet目标数组存在新增加的项则不增加,不存在则增加(数组中有mathcomputerupdate math时不增加,而update english时,数组中没有english,则增加)

db.student.update({"_id":3},{$addToSet:{course:{$each:

["math","english","Chinese"]}}}); 批量增加

7删除文档数据

db.student.remove({_id:10});删除id10的文档的数据。

8删除库中的集合

db.student.drop();

9、删除数据库

db.dropDatabase();

10Shellhelp

db.help();查看操作数据库的方法

db.student.help();查看操作集合的(student)方法

11mongodbapi

http://api.mongodb.org/js/2.1.2/index.html

12、数据库和集合命名规范

1、不能是空字符串

2、不能含有‘ ’、(空格)、,、$/、和O(空字符)

3、应全部小写

4、最多64个字节

5、数据库名不能与现有系统保留库同名。如adminconfiglocal

13ecllipse中装入mongodb插件

help-->install new soft-->add-->Mongodb,http://www.jumperz.net/update/



14、查找db.[documentName].find({条件},{键指定})

查找所有年龄在2527岁之间的学生

db.student2.find({"age":{$lte:27,$gte:25}},{"_id":0,"name":1,"age":1}); _id=0表示不显示 id


查找所有不是美国的学生

db.student.find({"Country":{$ne:"USA"}},{"_id":0,"name":1,"Country":1});


查询所有是美国和中国的学生

db.student.find({"Country":{$in:["USA","China"]}},{"_id":0,"name":1,"Country":1});


查询所有不是美国和中国的学生

db.student2.find({"Country":{$nin:["USA","China"]}},{"_id":0,"name":1,"Country":1});


查询所有数学成绩大于65或者英语成绩小于95的学生

db.student.find({$or:[{"Math":{$gt:65}},{"English":{$lt:95}}]},

{"_id":0,"name":1,"Math":1,"English":1});


查询所有性别为空的学生

db.student.find({"sex":{$in:[null]}},{"_id":0,"name":1});


查询所有名字为To的学生

db.student.find({"name":/To/},{"_id":0,"name":1});


查询所有学生名字不含字母a的学生

db.student.find({"name":{$not:/a/}},{"_id":0,"name":1});

查询数组book中有javac++的学生信息

db.student.find({"book":{$all:["java","C++"]}},{"_id":0,"name":1});


查询数组第二个值是java的学生信息

db.student.find({"book.1":"java"},{"_id":0,"name":1})


查询数组长度是2的学生信息

db.student.find({"book":{$size:2}},{"_id":0,"name":1});


查询名字含T的所有学生的书的数组的长度(游标)

var student = db.student2.find({"name":/T/});

while(student.hasNext()){print(student.next().book.length)};


查询学生的book数组中从下标1开始起共2个即book[1],book[2]

db.student2.find({"name":"Tom5"},{"_id":0,"name":1,"book":{$slice:[1,2]}})


查询学生的book数组中最后一个元素

db.student2.find({"name":"Tom5"},{"_id":0,"name":1,"book":{$slice:-1}})


查询前五条数据

db.student2.find({},{"_id":0,"name":1}).limit(5);


查询从第七条开始后三条数据即第7,8,9

db.student2.find({},{"_id":0,"name":1}).limit(3).skip(6);


查询的结果按年龄正序排序

db.student2.find({},{"_id":0,"name":1,"age":1}).sort({age:1});


查询的结果按年龄逆序排序

db.student2.find({},{"_id":0,"name":1,"age":1}).sort({age:-1});


快照的使用

db.student2.find({$query:{"name":"Tom5"},snapshot:true},{"_id":0,"name":1});

 

 


15、索引

var start = new Date();

for(var i=0;i<20000;i++){

db.student.insert({"number":i,"name":"student"+i});

}

var end = new Date();

print((end-start)+"ms");


建立索引,查找速度变快1是正序创建索引(正序:越早的创建时间),-1为倒序创建索引(逆序:越迟的创建时间)

db.student.ensureIndex({"number":1});


var start = new Date();

db.student.find({"number":15997});

var end = new Date();

print((end-start)+"ms");


索引的创建在提高查询性能的同时会影响插入的性能。对于经常查询少插入的文档可以考虑用索引。

 

创建逆序索引name,并指定该索引名字为studentname

db.student.ensureIndex({"name":-1},{"name":"studentname"});


创建唯一索引name

db.student.ensureIndex({"name":1},{"unique":true});


如果集合中已经有重复的文档,踢出重复值

db.student.ensureIndex({"name":1},{"unique":true,"dropDups":true}) ;


指定查询所使用的索引(name正序索引),指定索引必须是创建好的索引

db.student.find({"name":"student333"}).hint({"name":1});


查看本次查询所使用的索引和查询数据的状态信息

db.student.find({"name":"student333"}).explain();


查看索引

db.system.indexes.find();

db.system.namespaces.find();


不锁表创建索引

db.student.ensureIndex({"name":1},{"unique":true,"background":true})


删除索引

db.runCommand({"dropIndexes":"student",index:"name_1"});

批量删除

db.runCommand({"dropIndexes":"student",index:"*"});


 

db.map.find():

{ "_id" : ObjectId("55ae30a55e9fc03a8994fb34"), "gis" : { "x" : 185, "y" : 150 } }

创建2d索引,默认会建立[-180,180]的索引

db.map.ensureIndex({"gis":"2d"},{"min":-1,"max":200});


查询离点{70,180}最近的三个点

db.map.find({"gis":{$near:[70,180]}},{"gis":1,"_id":0}).limit(3);


查询以点(50,50)和点(190,190)为对角线的正方形中所有的点

db.map.find({"gis":{$within:{$box:[[50,50],[190,190]]}}},{"_id":0,"gis":1})


查询以(65,80)为点半径为50的圆内的点

db.map.find({"gis":{$within:{$center:[[65,80],50]}}},{"_id":0,"gis":1})

 



16、查询结果的个数

db.student.find().count();


去重操作

db.runCommand({distinct:”persons”,key:”country”}).values

Group使用

 




查询服务器版本号和主机操作系统

db.runCommand({buildInfo:1});


查询集合详细信息,大小,空间,索引

db.runCommand({collStats:"student"});



查看mongodb命令

db.listCommands();

http://localhost:28017/_command



查看操作本集合最后一次错误信息

db.runCommand({getLastError:”student”})



17、 固定集合

1、固定集合默认是没有索引的就算是_id也是没有索引的

2、由于不需分配新的空间,它的插入速度是非常快的

3、固定集合的顺序是确定的,导致查询速度是非常快的

4、最适合的是应用就是日志管理

 

5、创建固定集合

创建一个新的固定集合,大小是100字节,可以存储文档十个。

db.createCollection("myColl",{size:100,capped:true,max:10});

 

6、将一个普通集合转为一个固定集合。

db.runCommand({"convertToCapped":"student","size":10000});


7、反向排序,默认是插入顺序排序

db.student.find().sort({$natural:-1});

 

8、尾部游标,可惜shell不支持,javaphp等驱动是支持的



18、文件GridFS

1、上传一个文件(/home/xxlong/xxlong.txt上传到数据库中,并重新命名为b.txt)

控制台(/bin/bash)mongofiles -d xxlong_db -l "/home/xxlong/xxlong.txt" put "b.txt"

 

2、查看GridFS的文件存储状态

show collections;

====>

  fs.chunks

  fs.files





db.fs.chunks.find();

===>{ "_id" : ObjectId("55af7b9e9199bc7fc2000002"),

"files_id" : ObjectId("55af7b9e9199bc7fc2000001"),

"n" : 0,

"data" : BinData(0,"eHhsb25nIGxvbmcgaGVsbG8KMzExID

U2NyB5dWFuYmEKeHhsICB4aWFvCm

xvbmcJemkKdWVzdGMKCg==") }



db.fs.files.find();

===>{ "_id" : ObjectId("55af7b9e9199bc7fc2000001"),

"chunkSize" : 261120,

"uploadDate" : ISODate("2015-07-22T11:16:46.928Z"),

"length" : 58,

"md5" : "99eaa1494edf301e2c9bf51aee7f989e",

"filename" : "b.txt" }



查看文件内容

控制台:mongofiles -d xxlong_db get "b.txt" shell无法打开


查看所有文件

控制台:mongofiles -d xxlong_db list



删除已经存在的文件

控制台:mongofiles -d xxlong_db delete "b.txt"



19、服务器端运行eval

db.eval("function(name){return name}","xxl");

输出:xxl


20、保存js全局变量,system.js是一个特殊的集合

db.system.js.insert({"_id":"show_name","value":"xxlong"})

db.eval("return show_name") ===>xxlong



21导出数据

打开控制台(/bin/bash)

-d 指定要导出的库

-c 指定要导出的库的集合

-o 数据导出后存放的路径

-cvs指定导出的cvs格式

-q过滤导出

--type<json|csv|tsv>

切换到数据库目录下:

控制台:mongoexport --host 127.0.0.1 --port 27017  -d xxlong_db -c student -o /home/xxlong/xxl.json

22导入数据

mongoimport -d xxlong_db -c student --file /home/xxlong/xxl.json

切换到数据库目录下:

控制台:mongoimport --host 127.0.0.1 --port 27017 -d xxlong_db -c student110 --file "/home/xxlong/xxlong.json" 

 

23运行时备份

导出127.0.0.1服务下的27017的数据库xxlong数据库

切换到数据库目录下:

控制台:mongodump --host 127.0.0.1:27017 -d xxlong_db -o /home/xxlong/

/home/xxlong 目录下是数据库名(xxlong_db)的文件夹,里面是备份的数据


24、运行时恢复

切换到数据库目录下:

控制台:mongorestore --host 127.0.0.1:27017 -d xxlong_db /home/xxlong/xxlong_db


25、上锁

上锁可以是缓冲区中的数据全部放到数据库中

db.runCommand({fsync:1,lock:1})

26、解锁

db.fsyncUnlock();

27、数据修复

当停电等不可逆转灾难来临的时候,由于mongodb的存储结构导致会产生垃圾数据,在数据恢复以后这垃圾数据依然存在,这是数据库提供一个自我修复的能力。

db.repairDatabase();

原文地址:https://www.cnblogs.com/xxlong/p/4681148.html