这篇文章主要介绍了MongoDB入门教程,包含安装、经常使用命令、相关概念、使用技巧、常见操做等,是一篇比较好的入门文章,须要的朋友能够参考下
1、安装和配置
MongoDB 的官方下载站是 http://www.mongodb.org/downloads,能够去上面下载最新的安装程序
Windows 平台的安装
● 步骤一: 下载 MongoDB
点击上方官方下载地址, 并下载 Windows 版本mongodb
● 步骤二: 设置 MongoDB 程序存放目录
下载完成后, 解压到自定义文件夹,例: D:\mongodb\shell
● 步骤三: 设置数据文件存放目录
在 D:\mongodb\ 目录下建立 db 和 logs 文件夹 (和 bin 目录同级),
随后在 logs 文件夹内建立 mongodb.log 日志文件数据库
● 步骤四: 启动 MongoDB 服务, 做为 Windows 服务
express
//进入 cmd 控制台
D:/mongodb/bin>mongod.exe --logpath D:/mongodb/logs/mongodb.log --logappend
--dbpath D:/mongodb/db
--directoryperdb
--serviceName MongoDB
--install
--directoryperdb 指定每一个DB都会新建一个目录
安装完成后,就能够在 cmd 下用命令 net start MongoDB 和 net stop MongoDB 来启动和中止 MongoDB 了
● 步骤五: 客户端链接验证
打开 cmd 输入: D:/mongodb/bin>mongo.exe数组
D:/mongodb/bin>mongo.exe
MongoDB shell version: 2.4.8
connecting to: test
>
Linux 平台的安装
● 步骤一: 下载 MongoDB
点击上方官方下载地址, 并下载 Linux 版本app
● 步骤二: 设置 MongoDB 程序存放目录
下载完成后, 解压到自定义文件夹,例: /usr/local/mongo编辑器
● 步骤三: 设置数据文件存放目录
建立 /data/db 和 /data/logs 文件夹, 随后在 logs 文件夹内建立 mongodb.log 日志文件函数
● 步骤四: 启动 MongoDB 服务, 做为 Linux 服务随机启动
post
vi /etc/rc.local //使用vi 编辑器打开配置文件,并在其中加入下面一行代码
/usr/local/mongo/bin/mongod --dbpath=/data/db/ --logpath=/data/logs/mongodb.log --logappend&
安装完成后, 可使用 pkill mongod 来结束
2、数据逻辑结构
● MongoDB 的文档(document),至关于关系数据库中的一行记录。
● 多个文档组成一个集合(collection),至关于关系数据库的表。
● 多个集合(collection),逻辑上组织在一块儿,就是数据库(database)。
● 一个 MongoDB 实例支持多个数据库(database)。
● 默认端口: 27017
3、经常使用命令
选择数据库
use persons
显示当前数据库
db || db.getName()
删除当前数据库
db.dropDatabase()
显示当前数据库下的集合 Collections
show tables || show collections
显示当前 system.profile
show profile
显示当前数据库下的用户 Users
show users
添加用户
db.addUser(username, password)
删除用户
db.removeUser(username)
4、索引 ensureIndex()
//普通索引
db.persons.ensureIndex({name:1});
db.factories.insert({name: "xyz", metro: {city: "New York", state: "NY"}});
//文档式索引
db.factories.ensureIndex({metro : 1});
//嵌入式索引
db.factories.ensureIndex({"metro.city": 1});
//组合索引
db.things.ensureIndex({name: -1, qty: 1});
//惟一索引
db.user.ensureIndex({firstname: 1, lastname: 1}, {unique: true});
/* 当一个记录被插入到惟一性索引文档时,缺失的字段会以null为默认值被插入文档 */
db.things.save({lastname: "Smith"});
//下面这个操做将会失败,由于 firstname 上有惟一性索引,值为 null
db.things.save({lastname: "Jones"});
//查看索引
db.persons.getIndexes();
//删除全部索引
db.collection.dropIndexes();
//删除单个索引
db.collection.dropIndex({x: 1, y: -1});
5、增删改查等
//定义文档
>doc = {
"_id" : 1,
"author" : "sam",
"title" : "i love you",
"text" : "this is a test",
"tags" : [ "love", "test" ],
"comments" : [
{ "author" : "jim", "comment" : "yes" },
{ "author" : "tom", "comment" : "no" }
]
}
//插入文档
> db.posts.insert(doc);
//查找文档
> db.posts.find({'comments.author':'jim'});
查询 Query
//查询集合中的全部记录:
db.users.find({})
//查询出全部 “last_name” 属性值为 “Smith” 的文档记录
db.users.find({'last_name': 'Smith'})
查询选项
//返回除了 age 字段外的全部字段
> db.user.find( {},{ age : 0 } );
//返回 tags=tennis 除了 comments 的全部列
> db.posts.find( { tags : 'tennis' }, { comments : 0 } );
//返回 userid=16 的 name 字段
> db.user.find( { userid : 16 },{ name : 1 } );
//返回结果:
{ "_id" : 16, "name" : "user16" }
//返回 x=john 的全部 z 字段
> db.things.find( { x : "john" }, { z : 1 } );
//注: _id字段始终都会被返回,哪怕没有明确指定
条件表达式
1) <, <=, >, >=
// 大于: field > value
> db.collection.find( { "field" : { $gt : value } } );
//小于:field < value
> db.collection.find( { "field" : { $lt : value } } );
//大于等于: field >= value
> db.collection.find( { "field" : { $gte : value } } );
//小于等于:field <= value
> db.collection.find( { "field" : { $lte : value } } );
//区间查询 5 < field <= 10
> db.collection.find( { "field" : { $gt : 5, $lte : 10 } } );
$all 操做相似 $in 操做,可是不一样的是,$all操做要求数组里面的值所有被包含在返回的记录里面
> use test;
switched to db test
> db.things.insert( { a : [ 1, 2, 3 ] } );
> db.things.find();
{ "_id" : ObjectId("4de73360059e7f4bdf907cfe"), "a" : [ 1, 2, 3 ] }
> db.things.find( { a : { $all : [ 2, 3 ] } } );
{ "_id" : ObjectId("4de73360059e7f4bdf907cfe"), "a" : [ 1, 2, 3 ] }
> db.things.find( { a : { $all : [ 1, 2, 3 ] } } );
{ "_id" : ObjectId("4de73360059e7f4bdf907cfe"), "a" : [ 1, 2, 3 ] }
> db.things.find( { a : { $all : [ 1 ] } } );
{ "_id" : ObjectId("4de73360059e7f4bdf907cfe"), "a" : [ 1, 2, 3 ] }
> db.things.find( { a : { $all : [ 1, 2, 3, 4 ] } } );
>
>
$exists 操做检查一个字段是否存在
//userid 字段存在
> db.user.find( { userid : { $exists : true } } ).limit(1);
{ "_id" : 1, "name" : "user1", "userid" : 1, "age" : 20 }
//sex 字段不存在
> db.user.find( { sex : { $exists : true } } ).limit(1);
>
>
$mod 操做可让咱们简单的进行取模操做
//where子句
> db.user.find( "this._id%10==1" ).limit(5);
//$mod操做
> db.user.find( { _id : { $mod : [ 10, 1 ] } } ).limit(5);
$ne 意思是 不等于 (not equal)
> db.user.find().limit(2);
{ "_id" : 0, "name" : "user0", "userid" : 0, "age" : 20 }
{ "_id" : 1, "name" : "user1", "userid" : 1, "age" : 20 }
> db.user.find( { _id : { $ne : 0 } } ).limit(2);
{ "_id" : 1, "name" : "user1", "userid" : 1, "age" : 20 }
$in 操做相似于传统关系数据库中的IN
//数据库中有全部数组对应的记录
> db.user.find( { _id : { $in : [ 2, 3 ] } } ).limit(5);
{ "_id" : 2, "name" : "user2", "userid" : 2, "age" : 20 }
{ "_id" : 3, "name" : "user3", "userid" : 3, "age" : 20 }
$nin 跟 $in 操做相反
//扣掉 _id = 1/2/3/4 的记录
> db.user.find( { _id : { $nin : [ 1, 2, 3, 4 ] } } ).limit(5);
{ "_id" : 0, "name" : "user0", "userid" : 0, "age" : 20 }
{ "_id" : 5, "name" : "user5", "userid" : 5, "age" : 20 }
{ "_id" : 6, "name" : "user6", "userid" : 6, "age" : 20 }
$or
> db.user.find( { $or : [ { _id : 2 }, { name : 'user3' }, { userid : 4 } ] } ).limit(5);
{ "_id" : 2, "name" : "user2", "userid" : 2, "age" : 20 }
{ "_id" : 3, "name" : "user3", "userid" : 3, "age" : 20 }
{ "_id" : 4, "name" : "user4", "userid" : 4, "age" : 20 }
>
$nor 跟 $or 相反
> db.user.find( { $nor : [ { _id : 2 }, { name : 'user3' }, { userid : 4 } ] } ).limit(4);
{ "_id" : 0, "name" : "user0", "userid" : 0, "age" : 20 }
{ "_id" : 1, "name" : "user1", "userid" : 1, "age" : 20 }
{ "_id" : 5, "name" : "user5", "userid" : 5, "age" : 20 }
{ "_id" : 6, "name" : "user6", "userid" : 6, "age" : 20 }
>
$size 操做将会查询数组长度等于输入参数的数组
> db.things.find();
{ "_id" : ObjectId("4de73360059e7f4bdf907cfe"), "a" : [ 1, 2, 3 ] }
> db.things.find( { a : { $size : 3 } } );
{ "_id" : ObjectId("4de73360059e7f4bdf907cfe"), "a" : [ 1, 2, 3 ] }
> db.things.find( { a : { $size : 2 } } );
>
> db.things.find( { a : { $size : 1 } } );
>
$where
> db.mycollection.find( { $where : function() { return this.a == 3 || this.b == 4; } } );
//同上效果
> db.mycollection.find( function() { return this.a == 3 || this.b == 4; } );
$type 将会根据字段的 BSON 类型来检索数据
//返回 a 是字符串的记录
> db.things.find( { a : { $type : 2 } } );
//返回 a 是 int 类型的记录
> db.things.find( { a : { $type : 16 } } );
类型名称映射
● Double : 1
● String : 2
● Object : 3
● Array : 4
● Binary data : 5
● Object id :7
● Boolean :8
● Date :9
● Null : 10
● Regular expression : 11
● JavaScript code : 13
● Symbol : 14
● JavaScript code with scope : 15
● 32-bit integer : 16
● Timestamp : 17
● 64-bit integer : 18
● Min key : 255
● Max key : 127
Mongodb一样支持正则表达式进行检索
//检索name属性是以 u 开头,4 结尾的全部用户
> db.user.find( { name : /u.*4$/i } ).limit(2);
{ "_id" : 4, "name" : "user4", "userid" : 4, "age" : 20 }
{ "_id" : 14, "name" : "user14", "userid" : 14, "age" : 20 }
//一样效果的查询语句
> db.user.find( { name : { $regex : 'u.*4$', $options : 'i' } } ).limit(2);
{ "_id" : 4, "name" : "user4", "userid" : 4, "age" : 20 }
{ "_id" : 14, "name" : "user14", "userid" : 14, "age" : 20 }
//配合其余操做一块儿使用
> db.user.find( { name : { $regex : 'u.*4$', $options : 'i', $nin : [ 'user4' ] } } ).limit(2);
{ "_id" : 14, "name" : "user14", "userid" : 14, "age" : 20 }
排序
按照 last_name 属性进行升序排序返回全部文档
//1表示升序,-1表示降序
db.users.find( {} ).sort( { last_name : 1 } );
Group
//语法:
db.coll.group( {
cond : {filed:conditions},
key : {filed: true},
initial : {count: 0, total_time:0},
reduce : function(doc, out){ },
finalize : function(out){}
} );
参数说明:
Key :对那个字段进行
Group Cond :查询条件
Initial :初始化group计数器
Reduce :一般作统计操做
Finalize :一般都统计结果进行进一步操做,例如求平均值 Keyf:用一个函数来返回一个替代 KEY 的值
//例子
> db.test.group( {
cond : { "invoked_at.d" : { $gte : "2009-11", $lt : "2009-12" } },
key : {http_action: true},
initial : {count: 0, total_time:0},
reduce : function( doc, out ){ out.count++; out.total_time += doc.response_time },
finalize : function(out){ out.avg_time = out.total_time / out.count } } );
[
{
"http_action" : "GET /display/DOCS/Aggregation",
"count" : 1,
"total_time" : 0.05,
"avg_time" : 0.05
}
]
去重 相似于关系数据库中的 Distinct
> db.addresses.insert( { "zip-code" : 10010 } )
> db.addresses.insert( { "zip-code" : 10010 } )
> db.addresses.insert( { "zip-code" : 99701 } )
>
> db.addresses.distinct("zip-code");
[ 10010, 99701 ]
>
> //command 模式:
> db.runCommand( { distinct: 'addresses', key: 'zip-code' } )
{ "values" : [ 10010, 99701 ] }
>
> db.comments.save( { "user" : { "points" : 25 } } )
> db.comments.save( { "user" : { "points" : 31 } } )
> db.comments.save( { "user" : { "points" : 25 } } )
> db.comments.distinct("user.points");
[ 25, 31 ]
Mongodb 支持 skip 和 limit 命令来进行分页查询
//跳过前10条记录
> db.user.find().skip(10);
//每页返回8条记录
> db.user.find().limit(8);
//跳过前20条记录,而且每页返回10条记录
> db.user.find().skip(20).limit(8);
//下面这个语句跟上一条同样,只是表达不够清晰
> db.user.find({}, {}, 8, 20);
$elemMatch
> t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } )
{ "_id" : ObjectId("4b5783300334000000000aa9"), "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ] }
//一样效果
> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )
count()方法返回查询记录的总数
db.orders.count( { ord_dt : { $gt : new Date('01/01/2012') } } )
//一样效果
db.orders.find( { ord_dt : { $gt : new Date('01/01/2012') } } ).count()
//当查询语句用到了 skip() 和 limit() 方法的时候,
//默认状况下 count() 会忽略这些方法,若是想要计算这些方法,
//须要给 count() 方法传一个 true 做为参数
> db.user.find( { _id : { $lt : 20 } } ).skip(3).limit(9).count();
20
> db.user.find( { _id : { $lt : 20 } } ).skip(3).limit(9).count(true);
9
>
$slice
db.posts.find({}, {comments:{$slice: 5}}) // 前5条评论
db.posts.find({}, {comments:{$slice: -5}}) //后5条评论
db.posts.find({}, {comments:{$slice: [20, 10]}}) // 跳过20条, limit 10
db.posts.find({}, {comments:{$slice: [-20, 10]}}) // 后20条, limit 10
删除 Delete
Remove 操做用于从集合中删除记录
//删除一条记录
> db.stu.remove( { _id : 17 } );
//删除全部记录
> db.stu.remove( {} );
//某些状况下,当你在对一个记录执行 remove 操做的时候,
//可能会有 update 操做在这个记录上,这样就可能删除不掉这个记录,
//若是你以为这不尽人意,那么你能够在 remove 操做的时候加上 $atomic:
db.stu.remove( { rating : { $lt : 3.0 }, $atomic : true } );
更新 Update
db.collection.update( criteria, objNew, upsert, multi )
参数说明:
Criteria :用于设置查询条件的对象
Objnew :用于设置更新内容的对象
Upsert :若是记录已经存在,更新它,不然新增一个记录
Multi :若是有多个符合条件的记录,所有更新 注意:默认状况下,只会更新第一个符合条件的记录
save()
//若是存在更新它,若是不存在,新增记录
db.mycollection.save( { name : 'shawn' } );
$inc
{ $inc : { field : value } } //把field的值加一个value
> db.user.findOne( { _id : 0 } );
{ "_id" : 0, "name" : "user0", "userid" : 0, "age" : 22 }
> db.user.update( { _id : 0 }, { $inc : { age : 1 } } );
{ "_id" : 0, "name" : "user0", "userid" : 0, "age" : 23 }
$set
{ $set : { field : value } }
// 把field的值设置成value,当field不存在时,增长一个字段,
// 相似SQL的set操做,value支持全部类型
// 把上面的 age 改回到 20
> db.user.update( { _id : 0 }, { $set : { age : 20 } } );
{ "_id" : 0, "name" : "user0", "userid" : 0, "age" : 20 }
// 当 field 不存在时,增长一个字段
> db.user.update( { _id : 0 }, { $set : { sex : 'boy' } } );
{ "_id" : 0, "sex" : "boy", "name" : "user0", "userid" : 0, "age" : 20 }
$unset
{ $unset : { field : 1} } // 删除给定的字段field
//删除上一步增长的sex字段
> db.user.update( { _id : 0 }, { $unset : { sex : 1 } } );
{ "_id" : 0, "name" : "user0", "userid" : 0, "age" : 20 }
$push
{ $push : { field : value } }
// 若是 filed 是一个已经存在的数组,那么把 value 追加给 field
// 若是 field 原来不存在,那么新增 field 字段,把value的值赋给field
// 若是 field 存在,可是不是一个数组,将会出错
> db.sport.update( { _id : 0 }, { $push : { aihao : 'football' } } );
$pushAll
{ $pushAll : { field : value_array } }
// 功能同$push,只是这里的 value 是数组,至关于对数组里的每个值进行 $push 操做
$addToSet
{ $addToSet : { field : value } }
// 若是 filed 是一个已经存在的数组,而且 value 不在其中,那么把 value 加入到数组
// 若是 filed 不存在,那么把 value 当成一个数组形式赋给 field
// 若是 field 是一个已经存在的非数组类型,那么将会报错
$pop
{ $pop : { field : 1 } } //删除数组中最后一个元素
{ $pop : { field : -1 } } //删除数组中第一个元素
$pull
{ $pull : { field : _value } }
// 若是 field 是一个数组,那么删除符合 _value 检索条件的记录
// 若是 field 是一个已经存在的非数组,那么会报错
$pullAll
{ $pullAll : { field : value_array } } //同$push相似,只是value的数据类型是一个数组
$rename
{ $rename : { old_field_name : new_field_name }
// 重命名指定的字段名称,从1.7.2版本后开始支持
> db.user.update( { _id : 0 } , { $rename : { 'quantity' : 'qty'}});
特殊操做符:$
$ 操做符表明查询记录中第一个匹配条件的记录项
//例1 > db.t.find() { "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : "ABC", "comments" : [ { "by" : "joe", "votes" : 3 }, { "by" : "jane", "votes" : 7 } ] } > db.t.update( { 'comments.by' : 'joe' }, { $inc : { 'comments.$.votes' : 1 } }, false, true ) > db.t.find() { "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : "ABC", "comments" : [ { "by" : "joe", "votes" : 4 }, { "by" : "jane", "votes" : 7 } ] } //例2 > db.t.find(); { "_id" : ObjectId("4b9e4a1fc583fa1c76198319"), "x" : [ 1, 2, 3, 2 ] } > db.t.update( { x : 2 }, { $inc : { "x.$": 1 } }, false, true); > db.t.find(); { "_id" : ObjectId("4b9e4a1fc583fa1c76198319"), "x" : [ 1, 3, 3, 2 ] } //在数组中用 $ 配合 $unset操做 符的时候,效果不是删除匹配的元素,而是把匹配的元素变成了null,如: > db.t.insert( { x: [ 1, 2, 3, 4, 3, 2, 3, 4 ] } ) > db.t.find() { "_id" : ObjectId("4bde2ad3755d00000000710e"), "x" : [ 1, 2, 3, 4, 3, 2, 3, 4 ] } > db.t.update( { x : 3 }, { $unset : { "x.$" : 1 } } ) > t.find() { "_id" : ObjectId("4bde2ad3755d00000000710e"), "x" : [ 1, 2, null, 4, 3, 2, 3, 4 ] }