前言
笔者写这个博客主要是参考菜鸟网站runoob.com,是为了想快速学习了解MongoDB的一些基本知识,如果你想深入了解,推荐MongDB Mnaual系统学习MongDB.
1、简介
MongDB是开源的文档存储类型数据库。
2、安装启动
# curl -O https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.0.6.tgz
# tar -zxvf mongodb-linux-x86_64-3.0.6.tgz
# mv mongodb-linux-x86_64-3.0.6 /usr/local/mongodb/
# mkdir -p /usr/local/mongodb/data/db
# cat /etc/mongod.conf
[root@sht-sgmhadoopcm-01 mongodb]# cat /etc/mongod.conf systemLog: destination: file path: "/usr/local/mongodb/log/mongod.log" logAppend: true storage: dbPath: /usr/local/mongodb/data/db journal: enabled: true processManagement: fork: true pidFilePath: /usr/local/mongodb/data/db/mongod.pid net: port: 27017 bindIp: 0.0.0.0 setParameter: enableLocalhostAuthBypass: false
# bin/mongod --config /etc/mongod.conf
warning: bind_ip of 0.0.0.0 is unnecessary; listens on all ips by default
about to fork child process, waiting until server is ready for connections.
forked process: 21394
child process started successfully, parent exiting
# bin/mongo
> db.runoob.insert({x:10})
WriteResult({ "nInserted" : 1 })
> db.runoob.find()
{ "_id" : ObjectId("5bd2c9e8c0e1c2a4634de8bb"), "x" : 10 }
3、MongoDB基本概念
(1) 基本结构(与MySQL对比)
MongDB--db--collection--document--field
MySQL--db--table--row--column
[root@sht-sgmhadoopcm-01 mongodb]# bin/mongo
MongoDB shell version: 3.0.6
connecting to: test
list所有db
> show dbs
local 0.078GB
test 0.078GB
查看当前在哪个db下
> db
test
切换db
> use local
switched to db local
(2)ObjectId
ObjectId 类似唯一主键,可以很快的去生成和排序,包含 12 bytes,含义是:
前 4 个字节表示创建unix时间戳,格林尼治时间UTC时间,比北京时间晚了8小时
接下来的3个字节是机器标识码
紧接的两个字节由进程id组成PID
最后三个字节是随机数
这里表示的时间是UTC时间
> var newobject = ObjectId()
> newobject.getTimestamp()
ISODate("2018-10-26T08:47:59Z")
> newobject.str
5bd2d4bf6d79d6dd6eeb51b9
(3)时间函数
> var mydate1=new Date() #UTC时间
> mydate1
ISODate("2018-10-26T08:54:15.997Z")
> typeof mydate1
object
> var mydate2=ISODate() #UTC时间
> mydate2
ISODate("2018-10-26T08:55:45.199Z")
> typeof mydate2
object
返回一个时间类型的字符串
> var mydate1str = mydate1.toString()
> typeof mydate1str
string
> Date() #UTC+8
Fri Oct 26 2018 16:56:48 GMT+0800 (CST)
> ISODate()
ISODate("2018-10-26T08:57:04.144Z")
4、MongDB基本操作
(1)创建,删除DB
在MongoDB中,集合只有在内容插入后才会真正的创建
> use runoob
switched to db runoob
> db
runoob
> show dbs
local 0.078GB
test 0.078GB
> db.runoob.insert({"name":"jian"})
WriteResult({ "nInserted" : 1 })
> show dbs
local 0.078GB
runoob 0.078GB
test 0.078GB
> show dbs
local 0.078GB
runoob 0.078GB
test 0.078GB
删除DB
> db.dropDatabase()
{ "dropped" : "runoob", "ok" : 1 }
> show dbs
local 0.078GB
test 0.078GB
(2)创建、删除collection
> use test
switched to db test
> db.createCollection("collection1")
{ "ok" : 1 }
> show collections
collection1
runoob
system.indexes
创建固定大小,自动在 _id字段上创建索引,document数量为10000;
> db.createCollection("collection2", {capped:true, autoIndexId:true, size:6142800, max:10000})
{ "ok" : 1 }
在 MongoDB 中,你不需要创建集合。当你插入一些文档时,MongoDB 会自动创建集合
> db.collection3.insert({"key":"values"})
WriteResult({ "nInserted" : 1 })
> show tables
collection1
collection2
collection3
runoob
system.indexes
删除collection
> db.collection3.drop()
true
(3)插入,更新,删除document
a.插入document
>db.collection1.insert({title: 'MongoDB 教程', description: 'MongoDB 是一个 Nosql 数据库', by: '菜鸟教程', url: 'http://www.runoob.com', tags: ['mongodb', 'database', 'NoSQL'], likes: 100 }) > db.collection1.find() 通过定义个document变量来插入数据 >document_example=({title: 'Oracle 教程', description: 'Oracle 是一个 RDBMS 数据库', by: '菜鸟教程', url: 'http://www.runoob.com', tags: ['Oracle', 'database', 'RDBMS'], likes: 100 }) > db.collection1.insert(document_example) WriteResult({ "nInserted" : 1 })
b.更新document
修改匹配的第一条title内容 > db.collection1.update({'title':'MongoDB 教程'},{$set:{'title':'MongoDB'}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.collection1.find().pretty() 修改匹配整个集合的title内容 db.collection1.update({'title':'MongoDB 教程'},{$set:{'title':'MongoDB'}},{multi:true}) 根据_id更新id为56064f89ade2f21f36b03136 的文档数据: db.collection1.save({ "_id" : ObjectId("5bd81c443927ce142a81ff08"), "title" : "MongoDB", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "Runoob", "url" : "http://www.runoob.com", "tags" : [ "mongodb", "NoSQL" ], "likes" : 110 })
c.删除document
删除title为MongoDB的所有document记录
> db.collection1.remove({'title':'MongoDB'})
删除title为MongoDB的一个document记录
> db.collection1.remove({'title':'MongoDB 教程'},{justOne:1})
清空集合,删除所有的document
> db.collection1.remove({})
(4)查询find()
易读方式查询
> db.collection1.find().pretty()
指定条件查询docuemnt,返回所有满足条件的记录
> db.collection1.find({"title" : "Oracle 教程"})
指定条件查询docuemnt,返回第一条满足条件的记录
> db.collection1.findOne({"likes" : 100})
(5)一些常用的操作符
指定likes小于100的,
$gt -- greater than >
$gte -- gt equal >=
$lt -- less than <
$lte -- lt equal <=
$ne -- not equal !=
$eq -- equal =
> db.collection1.find({"likes":{$lt:100}})
and条件
> db.collection1.find({"title" : "MongoDB 教程","likes":{$gt:100}})
or条件
> db.collection1.find({$or:[{"likes":{$lt:90}},{"likes":{$gt:100}}]})
通过$type指定数据类型,2表示string类型的数据
> db.collection1.find({"title":{$type:2}})
limit(N)和skip(N)
> db.collection1.find().limit(3)
> db.collection1.find({},{"_id":0,"title":1,"url":1}).limit(2)
skip(N)跳过前三行,直接返回第四行及以后docuemnt
> db.collection1.find({},{"_id":0,"title":1,"url":1}).skip(3)
排序sort(),1为升序,-1为倒序
> db.collection1.find({},{"_id":0,"title":1,"likes":1}).sort({"likes":1})
> db.collection1.find({},{"_id":0,"title":1,"likes":1}).sort({"likes":-1})
(6)MongoDB索引createIndex()
创建单列索引
> db.collection1.createIndex({"title":1})
创建多列索引
> db.collection1.createIndex({"title":1,"likes":-1})
创建唯一索引
> db.collection1.createIndex({"_id":1},{unique:true})
(7)聚合函数aggregate()
> db.coll1.find() { "_id" : ObjectId("5bdb130c28a4a2aea6e37dcf"), "title" : "MongoDB Overview", "description" : "MongoDB is no sql database", "by_user" : "runoob.com", "url" : "http://www.runoob.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 } { "_id" : ObjectId("5bdb130c28a4a2aea6e37dd0"), "title" : "NoSQL Overview", "description" : "No sql database is very fast", "by_user" : "runoob.com", "url" : "http://www.runoob.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 10 } { "_id" : ObjectId("5bdb130c28a4a2aea6e37dd1"), "title" : "Neo4j Overview", "description" : "Neo4j is no sql database", "by_user" : "Neo4j", "url" : "http://www.neo4j.com", "tags" : [ "neo4j", "database", "NoSQL" ], "likes" : 750 } > db.coll1.aggregate([{$group : {_id : "$by_user", count : {$sum : 1}}}]) { "_id" : "Neo4j", "count" : 1 } { "_id" : "runoob.com", "count" : 2 } > db.coll1.aggregate([{$group : {_id : "$by_user", count : {$sum : "$likes"}}}]) { "_id" : "Neo4j", "count" : 750 } { "_id" : "runoob.com", "count" : 110 } 管道操作 > db.coll1.aggregate({ $project : {_id:0,title : 1 ,likes:10}}) { "title" : "MongoDB Overview", "likes" : 100 } { "title" : "NoSQL Overview", "likes" : 10 } { "title" : "Neo4j Overview", "likes" : 750 } $likes用于获取大于70小于或等于200记录,然后将符合条件的记录送到下一阶段$group管道操作符进行处理。 > db.coll1.aggregate( [{ $match : { likes : { $gt : 70, $lte : 200 } } },{ $group: { _id: null, count: { $sum: 1 } } }] ); { "_id" : null, "count" : 1 }
参考链接
http://www.runoob.com/mongodb/mongodb-tutorial.html
https://docs.mongodb.com/manual/introduction/