/ mongodb

mongodb

mongodb 常用操作

新增字段并设置默认值

$ sudo service mongodb start
$ mongo
> show dbs;
> use test;            # 连接到test数据库
> show collections;    
> db.users.find({})
# 例如新增 deleted 字段,默认值为 false
db.staffs.update({},{$set:{deleted:false}},false,true)
# 将所有员工生日定义为同一天
db.staffs.update({},{$set:{birthday:'1991-11-26T02:17:23.000Z'}},false,true)

查询 count

db.staffs.count({deleted: false})

更新

db.users.update({ 'username': '名字'}, { $set: { 'logintime': 1597826608000} });

数据查询

Making queries with find()

collection.find(query[[[, fields], options], callback]);
  • collection.find(query, callback);
  • collection.find(query, options, callback);
  • collection.find(query, fields, options, callback);

Where

  • query - is a query object, defining the conditions the documents need to apply
  • fields - indicates which fields should be included in the response (default is all)
  • options - defines extra logic (sorting options, paging etc.)
  • raw - driver returns documents as bson binary Buffer objects, default:false
  • callback has two parameters - an error object (if an error occured) and a cursor object.
collection.find({},{name: true, title: true},)
collection.find({"books.year":1714})

collection.findOne({_id: doc_id}, function(err, document) {
  console.log(document.name);
});

AND

当 find() 中传入多个键值对时,MongoDB就会将其作为 AND 查询处理。用法:

db.mycol.find({ key1: value1, key2: value2 }).pretty()

例如:

> db.post.find({"by":"shiyanlou","title": "MongoDB Overview"}).pretty()

OR

MongoDB中,OR 查询语句以 $or 作为关键词,用法如下:

> db.post.find(
   {
      $or: [
         {key1: value1}, {key2:value2}
      ]
   }
).pretty()

同时使用 AND 和 OR

> db.post.find({
    "likes": {$gt:10},
    $or: [
        {"by": "shiyanlou"},
        {"title": "MongoDB Overview"}
    ]
}).pretty()

安装mongodb

CentOS7

参考 Install MongoDB on Red Hat Enterprise or CentOS Linux

只需要将 baseurl 的相应值改为阿里云镜像地址:repo.mongodb.org => mirrors.aliyun.com/mongodb

Ubuntu 16 安装 MongoDB

Install MongoDB Community Edition on Ubuntu

需要注意的是,官方镜像太慢,我们换用阿里云镜像:https://repo.mongodb.org/apt/ubuntu => https://mirrors.aliyun.com/mongodb/apt/ubuntu

Now you can start the service and check its state by:

sudo systemctl start mongodb
sudo systemctl status mongodb

and finally enable it permanently by

sudo systemctl enable mongodb

如果需要重启

sudo systemctl restart mongodb

Ubuntu 14

安装步骤按照 mongodb 官方提供的文档,Ubuntu v14.04 中安装 mongodb 3.0

安装后的警告提示:

Server has startup warnings: 
2017-05-22T06:38:54.673+0000 I CONTROL  [initandlisten] 
2017-05-22T06:38:54.673+0000 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2017-05-22T06:38:54.673+0000 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2017-05-22T06:38:54.673+0000 I CONTROL  [initandlisten] 
2017-05-22T06:38:54.673+0000 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2017-05-22T06:38:54.673+0000 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2017-05-22T06:38:54.673+0000 I CONTROL  [initandlisten] 

按照提示更改下设置

sudo echo never >>  /sys/kernel/mm/transparent_hugepage/enabled
sudo echo never >>  /sys/kernel/mm/transparent_hugepage/defrag

重启下服务:

sudo service mongod restart

Mac OS 安装 mongodb

brew update
brew install mongodb

在启动 MongoDB 之前,需要创建一个用来存储 MongoDB 数据的目录。MongoDB 数据的默认存放位置是 /data/db (也需要手动创建)目录下

To have launchd start mongodb now and restart at login:
  brew services start mongodb
Or, if you don't want/need a background service you can just run:
  mongod --config /usr/local/etc/mongod.conf
sudo mkdir -p /data/db
mongod --dbpath /data/db
mongod

也可以更改为其它地方,比如说当前用户目录下,新建一个 data/db 目录用来存放 MongoDB 的数据:

cd ~
mkdir -p data/db
mongod --dbpath ~/data/db

查看帮助文档

mongod -h

安装文档

常用命令

# 进入 mongo shell
mongo

# 辅助命令
db.help();
db.getName();

# 切换/创建数据库
use site # 对应 export MONGO_URL=mongodb://localhost:27017/site

db.createCollection('users');
db.users.insert({ name: 'peter' });
db.users.find();

# 退出 mongo
exit

清空集合

db.rules.remove({})

服务

sudo service mongod start
sudo service mongod stop
sudo service mongod restart

用户及密码

MongoDB协议

Adjusting the Firewall

To allow access to MongoDB on its default port 27017 from everywhere, you could use sudo ufw allow 27017. However, enabling internet access to MongoDB server on a default installation gives unrestricted access to the whole database server.

In most cases, MongoDB should be accessed only from certain trusted locations, such as another server hosting an application. To accomplish this task, you can allow access on MongoDB's default port while specifying the IP address of another server that will be explicitly allowed to connect.

sudo ufw allow from your_other_server_ip/32 to any port 27017

备份

sudo vim /etc/cron.d/mongodb-backup
@daily root mkdir -p /var/backups/mongodb; mongodump --db todos(db名称) --out /var/backups/mongodb/$(date +'\%Y-\%m-\%d')

条件操作符

  • 大于 - $gt
  • 小于 - $lt
  • 大于等于 - $gte
  • 小于等于 - $lte

实验课程

  • 一个mongoDB可以创建多个数据库
  • 使用show dbs可以查看所有数据库的列表(刚建立的空数据库不会显示)
  • 执行db命令则可以查看当前数据库对象或者集合
  • 运行use命令可以连接到指定的数据库

文档

文档是mongoDB的核心,类似于SQLite数据库(关系数据库)中的每一行数据。多个键及其关联的值放在一起就是文档。在mongodb中使用一种类json的bson存储数据,bson数据可以理解为在json的基础上添加了一些json中没有的数据类型。例如:

{"company":"Chenshi keji"}

文档的关系

  • 嵌入:将两个文档分开,通过引用文档的_id字段来建立关系
  • 引用:将两个文档分开,通过引用文档的_id字段来建立关系

集合

集合就是一组文档的组合,就相当于是关系数据库中的表,在mongodb中可以存储不同的文档结构的文档 例:

{"company":"Chenshi keji"} {"people":"man","name":"peter"}
> db.createCollection("users") # 创建集合
> show collections
> db.users.drop() # 删除 users 集合

上面两个文档就可以存储在同一个集合中

元数据

数据库的信息存储在集合中,他们统一使用系统的命名空间:DBNAME.system.* DBNAME可用db或数据库名替代

DBNAME.system.namespaces :列出所有名字空间
DBNAME.system.indexs :列出所有索引
DBNAME.system.profile :列出数据库概要信息
DBNAME.system.users :列出访问数据库的用户
DBNAME.system.sources :列出服务器信息

ISODate

北京时间2017-10-19 18:26:56 对应存储为 ISODate("2017-10-09T08:26:56.782Z")

JavaScript's Date object supports the ISO date format, so as long as you have access to the date string, you can do something like this:

// javascript
var myDate = new Date("2017-10-09T08:26:56.782Z");
// Mon Oct 09 2017 16:26:56 GMT+0800 (中国标准时间)
// php 中 object(MongoDB\BSON\UTCDateTime)
echo $model->created_at->toDateTime()->format('Y-m-d H:i:s');

MongoDB's ISODate() is just a helper function that wraps a JavaScript date object and makes it easier to work with ISO date strings.

在 mongo shell 中:

ISODate("2017-10-09T08:26:56.782Z").toLocaleTimeString()
ISODate("2017-10-09T08:26:56.782Z").getHours()
ISODate("2017-10-09T08:26:56.782Z").getMinutes()