MongoDB修炼手册(二)——增删改篇

179 阅读5分钟

连接数据库

Windows下安装MongoDB是相当容易的事情,所以我这里就不再赘述。在安装并配置好系统环境之后,直接在命令行中输入mongo指令即可启动MongoDB。

C:\Users\fileName>mongo

创建数据库

一个use代码,就可以实现创建数据库并切换到那个数据库。如果已经存在同名的数据库,也就切换到了那个数据库,十分简便。

> use test
switched to db test

查询数据库

show dbs命令可以查询所有数据库,如果你创建了的数据库并没有显示,那你不妨试试往数据库里创建个集合再去show dbs就可以看到了。

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
test    0.000GB

删除数据库

偷偷的新增了一个test1的数据库,然后用db.dropDatabase()把它删掉

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
test    0.000GB
test1   0.000GB

> db.dropDatabase()
{ "ok" : 1 }

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
test    0.000GB

创建集合

创建集合的语法是db.createCollection(name, options),其中第一个参数是集合的名称,第二个参数是一个对象,可用于设置内存大小,不是必须设置的。

第二个参数对象包括三个字段,capped、size和max,capped是用于设置是否为固定集合,size是用于设值集合的内存大小,max是用于设置它的文档数量。当capped值为true时,size是必须设定的,且当内存达到size最大值或达到文档条数时,则会覆盖最早的那条记录。

例子:

> db.createCollection("col", {capped: true, size: 512, max: 10})
{ "ok" : 1 }

// 插入了是12条数据
> db.col.insert({"title": "hp"})
WriteResult({ "nInserted" : 1 })
> db.col.insert({"title": "hp1"})
WriteResult({ "nInserted" : 1 })
> db.col.insert({"title": "hp2"})
WriteResult({ "nInserted" : 1 })
> db.col.insert({"title": "hp3"})
WriteResult({ "nInserted" : 1 })
> db.col.insert({"title": "hp4"})
WriteResult({ "nInserted" : 1 })
> db.col.insert({"title": "hp5"})
WriteResult({ "nInserted" : 1 })
> db.col.insert({"title": "hp6"})
WriteResult({ "nInserted" : 1 })
> db.col.insert({"title": "hp7"})
WriteResult({ "nInserted" : 1 })
> db.col.insert({"title": "hp8"})
WriteResult({ "nInserted" : 1 })
> db.col.insert({"title": "hp9"})
WriteResult({ "nInserted" : 1 })
> db.col.insert({"title": "hp10"})
WriteResult({ "nInserted" : 1 })
> db.col.insert({"title": "hp11"})
WriteResult({ "nInserted" : 1 })

// 覆盖了前两条
> db.col.find()
{ "_id" : ObjectId("611c675657773730266b7eda"), "title" : "hp2" }
{ "_id" : ObjectId("611c675a57773730266b7edb"), "title" : "hp3" }
{ "_id" : ObjectId("611c675c57773730266b7edc"), "title" : "hp4" }
{ "_id" : ObjectId("611c675f57773730266b7edd"), "title" : "hp5" }
{ "_id" : ObjectId("611c676357773730266b7ede"), "title" : "hp6" }
{ "_id" : ObjectId("611c676757773730266b7edf"), "title" : "hp7" }
{ "_id" : ObjectId("611c676b57773730266b7ee0"), "title" : "hp8" }
{ "_id" : ObjectId("611c676e57773730266b7ee1"), "title" : "hp9" }
{ "_id" : ObjectId("611c677257773730266b7ee2"), "title" : "hp10" }
{ "_id" : ObjectId("611c677657773730266b7ee3"), "title" : "hp11" }
>

// 查询该集合是否为固定集合
> db.col.isCapped()
true

而已存在的非固定集合可以通过命令将其转换为固定集合

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

> db.toCappedCol.isCapped()
false


// 转换
> db.runCommand({"convertToCapped": "toCappedCol", size: 10000})
{ "ok" : 1 }

> db.toCappedCol.isCapped()
true

注意: 如果集合为固定集合,则无法删除数据

删除集合

> show tables
doc
col

> db.doc.drop()
true

> show tables
col

插入文档

我们所插入的文档的数据结构基本上和JSON的结构是一模一样的。而所有集合中存储的数据都是BSON(Binary JSON),是类似JSON的二进制形式,其最大大小为16MB。

上面创建集合的实例其实已经稍微的带了一下插入文档的操作。我们使用的是insert()方法插入,支持单个以及多个文档的插入。

3.2版本之后,新增了insertOne和insertMany来插入一个或多个文档。


> var mydoc = {
    name: {first: "yellow", last:"bird"},
    birth: new Date('May 24, 1995'),
    nickName: ['hp', 'fat guy', 'good man'],
 }
 
> db.col.insertOne(mydoc)
{
        "acknowledged" : true,
        "insertedId" : ObjectId("611ca7c213e48bd44324e7f2")
}
> var myDocs = [{    name: {    first: "blue",    last: "berry"  }}, {    name: {    first: "green",    last: "Arrow"  }}]

> db.col.insertMany(myDocs)
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("611cac4813e48bd44324e7f3"),
                ObjectId("611cac4813e48bd44324e7f4")
        ]
}

> db.col.find()
{ "_id" : ObjectId("611c676357773730266b7ede"), "title" : "hp6" }
{ "_id" : ObjectId("611c676757773730266b7edf"), "title" : "hp7" }
{ "_id" : ObjectId("611c676b57773730266b7ee0"), "title" : "hp8" }
{ "_id" : ObjectId("611c676e57773730266b7ee1"), "title" : "hp9" }
{ "_id" : ObjectId("611c677257773730266b7ee2"), "title" : "hp10" }
{ "_id" : ObjectId("611c677657773730266b7ee3"), "title" : "hp11" }
{ "_id" : ObjectId("611ca7c213e48bd44324e7f2"), "name" : { "first" : "yellow", "last" : "bird" }, "birth" : ISODate("1995-05-23T16:00:00Z"), "nickName" : [ "hp", "fat guy", "good man" ] }
{ "_id" : ObjectId("611cac4813e48bd44324e7f3"), "name" : { "first" : "blue", "last" : "berry" } }
{ "_id" : ObjectId("611cac4813e48bd44324e7f4"), "name" : { "first" : "green", "last" : "Arrow" } }

更新文档

更新文档的方法有两种:update()和save()。update()方法用于更新已存在的文档,save()方法通过传入文档来替换已有的文档,_id主键存在就更新,不存在则插入。

update()

update方法接受三个参数,第一个参数是查询条件,第二个参数是更新的文档内容,第三个是一个配置项,其中包括upsert和multi。upsert为true时,如果插入时不存在该记录,则插入该记录,如果为false,则不插入。

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

> db.col1.insert({"name":"yellowbird"})
WriteResult({ "nInserted" : 1 })

> db.col1.update({name: "yellowbird"}, {$set: {name: "hp"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.col1.find()
{ "_id" : ObjectId("611d361d13e48bd44324e7f5"), "name" : "hp" }

save()

save() 方法通过传入的文档来替换已有文档,_id 主键存在就更新,不存在就插入。这个写起来比update麻烦,个人不太推荐。

> db.col1.save({"_id": ObjectId("611d361d13e48bd44324e7f5"), "name": "saveHp"})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.col1.find()
{ "_id" : ObjectId("611d361d13e48bd44324e7f5"), "name" : "saveHp" }

删除文档

删除文档的操作比较简单,remove方法传入一个删除的条件即可

> db.col1.remove({"name":"saveHp"})
WriteResult({ "nRemoved" : 1 })

如果你想只删除检索到的第一条记录,则在后面的justOne中设置为1。

> db.col1.remove({name: "yellowbird"},{justOne: 1})
WriteResult({ "nRemoved" : 1 })

> db.col1.find()
{ "_id" : ObjectId("611d3a0d13e48bd44324e7f7"), "name" : "yellowbird" }