Mongodb 使用

安装

我这是Mac系统,直接选择brew安装就行了

brew install mongodb

[图片上传中...(image-20190601111727872.png-b280ab-1559898653894-0)]

然后运行

mongod

不过,上面运行是在前台,当关闭终端后就会停止。可以通过设置配置文件,使其保持在后台运行。

mongod  --dbpath=/data/db --logpath=/usr/local/var/lomongodb/mongo.log --logappend --fork

使用

1、连接数据库

第一种方式

首先,连接数据库

$ mongo 192.168.31.87:27017

如果设置了密码,则解开授权

> db.auth("root", “password”)

第二种方式:

$ mongo 192.168.31.87 --port 27017 -u root -p --authenticationDatabase admin

参考:https://www.jianshu.com/p/79caa1cc49a5

在这里,我遇到了问题,使用mongo --port 27017 -u root -p ,然后输入密码是不行的

2、创建数据库

> use test

如果数据库存在,则切换到此数据库;如果不存在,则创建数据库并切换到此数据库

> db

test

上面命令会显示当前使用的数据库

> show dbs

admin 0.000GB

config 0.000GB

local 0.000GB

上面命令会显示有哪些数据库,当插入一条数据后,就会显示出test库

3、集合

Mongodb中的集合,相当于Mysql中的表。创建集合使用createCollection()方法,格式:

db.createCollection(name, options)

参数说明:

  • name: 要创建的集合名称
  • options: 可选参数,指定有关内存大小及索引的选项

option 有如下参数:


image.png

在插入文档时,MongoDB首先检查固定集合的size字段,然后检查max字段

1、创建集合

> db.createCollection("test")
{ "ok" : 1 }

> db.createCollection("col", {capped: true, autoIndexId: true, size: 8000000, max:100})
{
    "note" : "the autoIndexId option is deprecated and will be removed in a future release",
    "ok" : 1
}

# 插入文档时,会自动创建集合
> db.student.insert({"name": "jack"})
WriteResult({ "nInserted" : 1 })

2、显示当前数据库下的集合

> show collections
col
student
test

3、删除集合

> db.col.drop()
true
> show collections
student
test

4、文档

MongoDB中的文档就相当于Mysql中的一条记录。文档的数据结构和JSON基本一样。

1、插入文档

MongoDB使用insert()或save()方法向集合中插入文档,语法如下:

db.collection.insert(document)

具体实践如下:

> db.test.insert({"name":"Jack", "height": 1.78})
WriteResult({ "nInserted" : 1 })

2、查询文档

查询使用的是find()方法,语法:

db.collection.find(query, projection)
  • query: 可选,使用查询操作符指定查询条件
  • projection: 可选,使用投影操作符指定返回的键

如果需要易读的方式来读取数据,可以使用pretty()方法,使用如下:

db.collection.find().pretty()

具体实践如下:

> db.test.find()
{ "_id" : ObjectId("5cf1f122e3f016c5abfb73c3"), "name" : "Jack", "height" : 1.78 }

> db.test.find().pretty()
{
    "_id" : ObjectId("5cf1f122e3f016c5abfb73c3"),
    "name" : "Jack",
    "height" : 1.78
}

> db.test.find({'name': 'Jack'}).pretty()
{
    "_id" : ObjectId("5cf1f122e3f016c5abfb73c3"),
    "name" : "Jack",
    "height" : 1.78
}

3、更新文档

https://stackoverflow.com/questions/30605638/why-does-upsert-a-record-using-update-one-raise-valueerror

5 备份数据

mongodump -h 192.168.31.87 -d xqxd_data -u root --authenticationDatabase admin

你可能感兴趣的:(Mongodb 使用)