mongodb 入门

mongodb

mongodb 是由 c++ 语言编写的一种 “非关系型数据库”

www.mongodb.com/download-center

启动 mongodb

下载后,在 bin 文件夹中找到 mongodb 文件,它既是数据库引擎程序。下面是一个最简单启动命令

mongod  --dbpath "./data" --logpath "./log" --auth

参数:

--dbpath 指在当前 data 目录下生成数据库文件。

--logpath 指定日志目录

--auth 指登录时,是否要进行登录认证.初次启动可不填

当然还有很多其他参数 可参见:docs.mongodb.com/v3.2/tutorial/manage-mongodb-processes/

这样写成命令固然可以,但是我们更喜欢使用配置文件来启动 mongodb

mongod --config /etc/mongod.conf
mongod -f /etc/mongod.conf

下面是一个配置文件的例子:

processManagement:
   fork: true
net:
   bindIp: 127.0.0.1
   port: 27017
storage:
   dbPath: /srv/mongodb
systemLog:
   destination: file
   path: "/var/log/mongodb/mongod.log"
   logAppend: true
storage:
   journal:
      enabled: true

mongodb 同时支持 ini 格式的配置文件

fork = true
bind_ip = 127.0.0.1
port = 27017
quiet = true
dbpath = /srv/mongodb
logpath = /var/log/mongodb/mongod.log
logappend = true
journal = true

更多配置可参见 docs.mongodb.com/v3.2/administration/configuration/

mongo booster

mongo booster 是一款 mongodb 的可视化管理工具。

下载地址:www.mongobooster.com

使用 mongo 工具连接数据库

除了使用上述的 mongo booster 来链接 mongo server 外 官方提供了一个命令行连接工具 mongo 它也在 bin 目录下。

./mongo
./mongo localhost:27017/test
./mongo username:pwd@localhost:27017/test

mongo 中的常用命令:

show dbs //返回数据库名称
show collections //返回当前数据库中的所有集合(表)
show users //返回当前数据库中的用户
db.help()

数据操作

插入数据

我们使用 db.<collection>.insert(<document>) 来向某集合插入一条文档.

db.student.insert({name:"tom",age:8,class:"1-2"});

当需要一次性插入多条文档时,可以使用 insertMany(<Array>);

db.student.insertMany([{name:"tom",age:8,class:"1-2"},{name:"jerry",age:9,class:"2-1"}]);

数据删除

使用 db.<collection>.remove(<condition>) 来删除文档,注意一旦删除不可恢复.

db.student.remove(); //将 student 中的全部文档删除,但保留集合
db.student.drop() //删除 student 集合

数据更新

一般我们会用到 updatesave 这 2 种方法进行数据更新.

使用 db.<collection>.update(<condition>,<document>,<option>),

db.student.update(
      {name:"tom"},
      {name:"jerry"},
      {
         upsert: <boolean>, //如果 <condition> 中没有找到,则 insert 一条
         multi: <boolean>, //是否将所有匹配到的数据都进行更改默认 false
      });

使用 db.<collection>.save(<document>) 用指定的文档来替换,如果指定文档中没有 _id 字段则执行 insert 它和 upsert 的区别在于 save 只比较 _id 字段.

//执行三遍
db.student.save({name:"tom"});
db.student.save({name:"tom"});
db.student.save({name:"tom"});

//会 insert 3 条
db.student.find();

>{name:"tom"}
>{name:"tom"}
>{name:"tom"}

db.student.save({_id:ObjectId("52064f89ad42f24f36203136"),name:"jerry"});

//执行的是 update
>WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
留言:

称呼:*

邮件:

网站:

内容: