一.插入
Insert()方法
要将数据插入到 MongoDB 集合中,需要使用 MongoDB 的 insert()
或save()
方法。
语法
insert()
命令的基本语法如下:
>db.COLLECTION_NAME.insert(document)
示例
>db.mycol.insert({
_id: 100,
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by: 'yiibai tutorials',
url: 'http://www.yiibai.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100,
})
这里mycol
是集合的名称,在前一章中所创建的。如果数据库中不存在集合,则MongoDB将创建此集合,然后将文档插入到该集合中。
在插入的文档中,如果不指定_id
参数,那么 MongoDB 会为此文档分配一个唯一的ObjectId。
_id
为集合中的每个文档唯一的12
个字节的十六进制数。 12
字节划分如下 -
_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id,
3 bytes incrementer)
要在单个查询中插入多个文档,可以在insert()
命令中传递文档数组。如下所示 -
> db.mycol.insert([
{
_id: 101,
title: 'MongoDB Guide',
description: 'MongoDB is no sql database',
by: 'yiibai tutorials',
url: 'http://www.yiibai.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
},
{
_id: 102,
title: 'NoSQL Database',
description: "NoSQL database doesn't have tables",
by: 'yiibai tutorials',
url: 'http://www.yiibai.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 210,
comments: [
{
user:'user1',
message: 'My first comment',
dateCreated: new Date(2017,11,10,2,35),
like: 0
}
]
},
{
_id: 104,
title: 'Python Quick Guide',
description: "Python Quick start ",
by: 'yiibai tutorials',
url: 'http://www.yiibai.com',
tags: ['Python', 'database', 'NoSQL'],
likes: 30,
comments: [
{
user:'user1',
message: 'My first comment',
dateCreated: new Date(2018,11,10,2,35),
like: 590
}
]
}
])
要插入文档,也可以使用db.post.save(document)
。 如果不在文档中指定_id
,那么save()
方法将与insert()
方法一样自动分配ID的值。如果指定_id
,则将以save()
方法的形式替换包含_id
的文档的全部数据。
其它插入文档的方法
db.collection.insertOne()方法
db.collection.insertOne()
方法将单个文档插入到集合中。以下示例将新文档插入到库存集合中。 如果文档没有指定_id
字段,MongoDB会自动将_id
字段与ObjectId
值添加到新文档。
db.inventory.insertOne(
{ item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
)
db.collection.insertOne()
方法返回包含新插入的文档的`_id```字段值的文档。
执行结果如下 -
> db.inventory.insertOne(
... { item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
... )
{
"acknowledged" : true,
"insertedId" : ObjectId("5955220846be576f199feb55")
}
>
db.collection.insertMany()方法
db.collection.insertMany()
方法将多个文档插入到集合中,可将一系列文档传递给db.collection.insertMany()
方法。以下示例将三个新文档插入到库存集合中。如果文档没有指定_id
字段,MongoDB会向每个文档添加一个ObjectId值的_id
字段。
db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } },
{ item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },
{ item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }
])
insertMany()
返回包含新插入的文档_id
字段值的文档。执行结果如下 -
> db.inventory.insertMany([
... { item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } },
... { item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },
... { item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }
... ])
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("59552c1c46be576f199feb56"),
ObjectId("59552c1c46be576f199feb57"),
ObjectId("59552c1c46be576f199feb58")
]
}
>
二.查找
find()方法
要从MongoDB集合查询数据,需要使用MongoDB的find()
方法。
语法
find()
命令的基本语法如下:
>db.COLLECTION_NAME.find(document)
find()
方法将以非结构化的方式显示所有文档。
pretty()方法
要以格式化的方式显示结果,可以使用pretty()
方法。
语法
> db.mycol.find().pretty()
示例
>db.mycol.find().pretty()
{
"_id": 100,
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",
"by": "yiibai tutorials",
"url": "http://www.yiibai.com",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100"
}
>
除了find()
方法外,还有一个findOne()
方法,它只返回一个文档。
MongoDB 与 RDBMS的等效 Where 子句
要在一些条件的基础上查询文档,可以使用以下操作。
操作 | 语法 | 示例 | RDBMS等效语句 |
---|---|---|---|
相等 | {<key>:<value>} | db.mycol.find({"by":"yiibai"}).pretty() | where by = 'yiibai' |
小于 | {<key>:{$lt:<value>}} | db.mycol.find({"likes":{$lt:50}}).pretty() | where likes < 50 |
小于等于 | {<key>:{$lte:<value>}} | db.mycol.find({"likes":{$lte:50}}).pretty() | where likes <= 50 |
大于 | {<key>:{$gt:<value>}} | db.mycol.find({"likes":{$gt:50}}).pretty() | where likes > 50 |
大于等于 | {<key>:{$gte:<value>}} | db.mycol.find({"likes":{$gte:50}}).pretty() | where likes >= 50 |
不等于 | {<key>:{$ne:<value>}} | db.mycol.find({"likes":{$ne:50}}).pretty() | where likes != 50 |
下面我们将对上表中的所有操作演示 -
MongoDB中的AND操作符
语法
在find()
方法中,如果通过使用’,
‘将它们分开传递多个键,则 MongoDB 将其视为AND
条件。 以下是AND
的基本语法 -
>db.mycol.find(
{
$and: [
{key1: value1}, {key2:value2}
]
}
).pretty()
示例
以下示例将显示由“yiibai tutorials
”编写并且标题为“MongoDB Overview”的所有教程。
> db.mycol.find({$and:[{"by":"yiibai tutorials"},{"title": "MongoDB Overview"}]}).pretty()
{
"_id" : 100,
"title" : "MongoDB Overview",
"description" : "MongoDB is no sql database",
"by" : "yiibai tutorials",
"url" : "http://www.yiibai.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
>
对于上面给出的例子,等效的SQL where
子句是 -
SELECT * FROM mycol where by ='yiibai tutorials' AND title ='MongoDB Overview'
可以在find
子句中传递任意数量的键值。
MongoDB中的OR操作符
语法
在要根据OR
条件查询文档,需要使用$or
关键字。 以下是OR
条件的基本语法 -
>db.mycol.find(
{
$or: [
{key1: value1}, {key2:value2}
]
}
).pretty()
示例
以下示例将显示由“yiibai tutorials
”编写或标题为“MongoDB Overview”的所有教程。
>db.mycol.find({$or:[{"by":"yiibai tutorials"},{"title": "MongoDB Overview"}]}).pretty()
{
"_id": 100,
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",
"by": "yiibai tutorials",
"url": "http://www.yiibai.com",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100"
}
>
使用 AND 和 OR 条件一起
示例
以下示例将显示likes
大于10
以及标题是“MongoDB Overview
”或者“yiibai tutorials
”的所有文档。 等价SQL where子句为 -
SELECT * FROM mycol where likes> 10 AND(by ='yiibai tutorials' OR title ='MongoDB Overview')
>db.mycol.find({"likes": {$gt:10}, $or: [{"by": "yiibai tutorials"},
{"title": "MongoDB Overview"}]}).pretty()
{
"_id": 100,
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",
"by": "yiibai tutorials",
"url": "http://www.yiibai.com",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100"
}
>
查询嵌入/嵌套文档
这里演示如何使用:db.collection.find()
方法对嵌入/嵌套文档的查询操作的示例。 此页面上的示例使用inventory
集合。要填充库存(inventory
)集合以准备一些数据,请运行以下命令:
db.inventory.insertMany( [
{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
]);
匹配嵌入/嵌套文档
要在作为嵌入/嵌套文档的字段上指定相等条件,请使用查询过滤器文档{<field>:<value>}
,其中<value>
是要匹配的文档。
例如,以下查询选择字段size
等于{ h: 14, w: 21, uom: "cm" }
的所有文档:
db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )
整个嵌入式文档中的相等匹配需要精确匹配指定的<value>
文档,包括字段顺序。
例如,以下查询与库存(inventory
)集合中的任何文档不匹配:
db.inventory.find( { size: { w: 21, h: 14, uom: "cm" } } )
查询嵌套字段
要在嵌入/嵌套文档中的字段上指定查询条件,请使用点符号(“field.nestedField
”)。
在嵌套字段上指定等于匹配
以下示例选择在size
字段中嵌套的字段uom
等于“in
”的所有文档:
db.inventory.find( { "size.uom": "in" } )
使用查询运算符指定匹配
查询过滤器文档可以使用查询运算符来指定,如以下形式的条件:
{ <field1>: { <operator1>: <value1> }, ... }
以下查询使用size
字段中嵌入的字段h
中的小于运算符($lt
):
db.inventory.find( { "size.h": { $lt: 15 } } )
指定AND条件
以下查询选择嵌套字段h
小于15
的所有文档,嵌套字段uom
等于“in
”,status
字段等于“D
”:
db.inventory.find( { "size.h": { $lt: 15 }, "size.uom": "in", status: "D" } )
三.修改
MongoDB Update()方法
update()
方法更新现有文档中的值。
语法
update()
方法的基本语法如下 -
> db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)
示例
考虑mycol
集合具有以下数据 -
> db.mycol.find({}, {'_id':1, 'title':1})
{ "_id" : 100, "title" : "MongoDB Overview" }
{ "_id" : 101, "title" : "MongoDB Guide" }
{ "_id" : 102, "title" : "NoSQL Database" }
{ "_id" : 104, "title" : "Python Quick Guide" }
>
以下示例将为标题为“MongoDB Overview
”的文档设置为“New Update MongoDB Overview
”。
> db.mycol.find({'title':'MongoDB Overview'},{'_id':1, 'title':1})
{ "_id" : 100, "title" : "MongoDB Overview" }
> # 更新操作
> db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New Update MongoDB Overview'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> # 查询更新后的结果 -
> db.mycol.find({'_id':100},{'_id':1, 'title':1})
{ "_id" : 100, "title" : "New Update MongoDB Overview" }
>
默认情况下,MongoDB只会更新一个文档。要更新多个文档,需要将参数’multi
‘设置为true
。
>db.mycol.update({'title':'MongoDB Overview'},
{$set:{'title':'New Update MongoDB Overview'}},{multi:true})
MongoDB Save()方法
save()
方法使用save()
方法中传递的文档数据替换现有文档。
语法
MongoDB save()
方法的基本语法如下所示:
>db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})
以下示例将_id
为 100
的文档使用新的文档替换。
db.mycol.save(
{
"_id" : 100, "title":"Update By Save()Method.", "by":"yiibai.com"
}
)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
db.mycol.find({'_id':100}, {'_id':1, 'title':1})
{ "_id" : 100, "title" : "Update By Save()Method." }
四.删除
remove()方法
MongoDB中的 remove()
方法用于从集合中删除文档。 remove()
方法接受两个参数。 一个是删除条件,第二个是标志:justOne
。
- criteria - (可选)符合删除条件的集合将被删除。
- justOne - (可选)如果设置为
true
或1
,则只删除一个文档。
语法
remove()
方法的基本语法如下 -
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
假设mycol
集合具有以下数据。
> db.mycol.find({}, {'_id':1, 'title':1})
{ "_id" : 101, "title" : "MongoDB Guide" }
{ "_id" : 102, "title" : "NoSQL Database" }
{ "_id" : 104, "title" : "Python Quick Guide" }
{ "_id" : 100, "title" : "Update By Save()Method." }
>
以下示例将删除_id
为“100
”的文档。
> db.mycol.find({}, {'_id':1, 'title':1})
{ "_id" : 101, "title" : "MongoDB Guide" }
{ "_id" : 102, "title" : "NoSQL Database" }
{ "_id" : 104, "title" : "Python Quick Guide" }
{ "_id" : 100, "title" : "Update By Save()Method." }
>
> db.mycol.remove({'_id':100})
WriteResult({ "nRemoved" : 1 })
> db.mycol.find({}, {'_id':1, 'title':1})
{ "_id" : 101, "title" : "MongoDB Guide" }
{ "_id" : 102, "title" : "NoSQL Database" }
{ "_id" : 104, "title" : "Python Quick Guide" }
>
只删除一条文档记录
如果有多条记录,并且只想删除第一条记录,则在remove()
方法中设置justOne
参数。
>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)
删除所有文档记录
删除所有文档记录,可在remove()
方法中设置justOne
参数。
如果不指定删除条件,MongoDB 将删除集合中的所有文档。 这相当于SQL的truncate
命令。
>db.mycol.remove()
>db.mycol.find()
>