mongodb是一个文档数据库(nosql),用户可以随意创建任何格式的文档,不像关系数据库那样需要先有表scheme,后续表变更也麻烦,容易出错。特别适合摸索期的团队开发。简单使用说明如下:
基础概念
- 数据库: 关系数据库中的数据库
- 集合: 关系数据库中的表
- 文档: 关系数据库中的记录
- 字段: 关系数据库中的字段或者列,mongo字段值可以是另一个文档,关系数据库不能
操作 | 函数名 | rdb关键字 |
---|---|---|
创建 | insert | insert |
删除 | remove | delete |
修改 | update | update |
查询 | find | select |
删除表/集合 | drop | drop |
删除数据库 | dropDatabase | drop |
下载安装
去 https://www.mongodb.com/try/download/community 下载,然后解压
启动
$ cd /path/to/mongodb
$ ./bin/mongod --dbpath data
客户端连接
$ ./bin/mongo
>
> show databases;
admin 0.000GB
config 0.000GB
local 0.000GB
> use test // 此处test不需要创建
switched to db test
CURD
1. 插入数据
db.COLLECTION_NAME.insert(document)
> db.user.insert({'nickname': 'hello'})
WriteResult({ "nInserted" : 1 })
> db.user.insert({'nickname': 'world'})
WriteResult({ "nInserted" : 1 })
> show databases;
admin 0.000GB
config 0.000GB
golden_ludo 0.001GB
local 0.000GB
test 0.000GB
> show collections
user
>
2. 查询数据
db.collection.find(query, projection)
query :可选,使用查询操作符指定查询条件
projection :可选,使用投影操作符指定返回的键。查询时返回文档中所有键值, 只需省略该参数即可(默认省略)。
> db.user.find()
{ "_id" : ObjectId("6278722304cf7fc953e93cba"), "nickname" : "hello" }
{ "_id" : ObjectId("6278722c04cf7fc953e93cbb"), "nickname" : "world" }
> db.user.find({'nickname': 'hello'})
{ "_id" : ObjectId("6278722304cf7fc953e93cba"), "nickname" : "hello" }
3.更新数据
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>
}
)
- query : update的查询条件,类似sql update查询内where后面的。
- update : update的对象和一些更新的操作符(如
inc...)等,也可以理解为> - sql update查询内set后面的
- upsert : 可选,这个参数的意思是,如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入。
- multi : 可选,mongodb 默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新。
- writeConcern :可选,抛出异常的级别。
> db.user.update({'nickname': 'hello'}, {$set: {'nickname': 'hi', 'age': 25}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.user.find({'nickname': 'hello'}).pretty()
> db.user.find({'nickname': 'hi'}).pretty()
{
"_id" : ObjectId("6278722304cf7fc953e93cba"),
"nickname" : "hi",
"age" : 25
}
3.删除数据
db.collection.remove(
<query>,
<justOne>
)
或者
db.collection.remove(
<query>,
{
justOne: <boolean>,
writeConcern: <document>
}
)
- query :(可选)删除的文档的条件。
- justOne : (可选)如果设为 true 或 1,则只删除一个文档,如果不设置该参数,或使用默认值 false,则删除所有匹配条件的文档。
- writeConcern :(可选)抛出异常的级别。
> db.user.find();
{ "_id" : ObjectId("6278722304cf7fc953e93cba"), "nickname" : "hi", "age" : 25 }
{ "_id" : ObjectId("6278722c04cf7fc953e93cbb"), "nickname" : "world" }
> db.user.remove({'nickname': 'null'});
WriteResult({ "nRemoved" : 0 })
> db.user.remove({'nickname': 'world'});
WriteResult({ "nRemoved" : 1 })
> db.user.find();
{ "_id" : ObjectId("6278722304cf7fc953e93cba"), "nickname" : "hi", "age" : 25 }
删除表(collection)
> show collections
user
> db.user.drop();
true
> show collections;
删除数据库
> db.dropDatabase();
{ "ok" : 1 }
网友评论