MongoDB基本操作
MongoDB基本操作
MongoDB 数据库操作
操作命令 | 作用 |
---|---|
use DATABASE_NAME | 如果数据库不存在,则创建数据库,否则切换到指定数据 库。 |
show dbs | 查看所有数据库 |
db | 显示当前数据库 |
db.dropDatabase() | 删除当前数据库 |
PS:刚创建的数据库并不在数据库的列表中, 要显示它,我们需要向数据库插入一些数据
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
test 0.000GB
> use lalaku
switched to db lalaku
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
test 0.000GB
> db
lalaku
> db.table01.insert({"name":"asdas"})
WriteResult({ "nInserted" : 1 })
> show dbs
admin 0.000GB
config 0.000GB
lalaku 0.000GB
local 0.000GB
test 0.000GB
> db.dropDatabase()
{ "ok" : 1 }
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
test 0.000GB
>
MongoDB 中默认的数据库为 test,如果你没有创建新的数据库,集合将存放在 test 数据库中。
注意: 在 MongoDB 中,集合只有在内容插入后才会创建! 就是说,创建集合(数据表)后要再插入一个文档(记录),集合才会真正创建。
MongoDB 集合操作
操作命令 | 作用 |
---|---|
db.createCollection | 创建集合 |
show collections | 查看当前库有多少集合 |
show tables | 查看当前库有多少集合 |
db.collection.drop() | 删除集合 |
db.collection1.renameCollection( " collection2" ) | 将集合名 collection1 命名为 collection2. |
创建集合
MongoDB 中使用 createCollection() 方法来创建集合。
语法格式:
db.createCollection(name, options)
参数说明:
- name: 要创建的集合名称
- options: 可选参数, 指定有关内存大小及索引的选项
options 可以是如下参数:
字段 | 类型 | 描述 |
---|---|---|
capped | 布尔 | (可选)如果为 true,则创建固定集合。固定集合是指有着固定大小的集合,当达到最大值时,它会自动覆盖最早的文档。 当该值为 true 时,必须指定 size 参数。 |
autoIndexId | 布尔 | 3.2 之后不再支持该参数。(可选)如为 true,自动在 _id 字段创建索引。默认为 false。 |
size | 数值 | (可选)为固定集合指定一个最大值,即字节数。 如果 capped 为 true,也需要指定该字段。 |
max | 数值 | (可选)指定固定集合中包含文档的最大数量。 |
在插入文档时,MongoDB 首先检查固定集合的 size 字段,然后检查 max 字段。
实例
在 test 数据库中创建 xixi 集合:
> use test
switched to db test
> show tables
something
> db.createCollection("xixi")
{ "ok" : 1 }
如果要查看已有集合,可以使用 show collections 或 show tables 命令:
> show collections
something
xixi
下面是带有几个关键参数的 createCollection() 的用法:
创建固定集合 mycol,整个集合空间大小 6142800 B, 文档最大个数为 10000 个。
> db.createCollection("mycol", { capped : true, autoIndexId : true, size : 6142800, max : 10000 } )
{
"note" : "The autoIndexId option is deprecated and will be removed in a future release",
"ok" : 1
}
> show tables
mycol
something
xixi
>
在 MongoDB 中,你不需要创建集合。当你插入一些文档时,MongoDB 会自动创建集合。
> db.mycol2.insert({"name" : "heihei"})
WriteResult({ "nInserted" : 1 })
> show tables
mycol
mycol2
something
xixi
>
删除集合
语法格式:
db.collection.drop()
参数说明:
- 无
返回值
如果成功删除选定集合,则 drop() 方法返回 true,否则返回 false。
实例
> show tables
mycol
mycol2
something
xixi
>
接着删除集合 mycol2 :
>db.mycol2.drop()
true
>
通过 show collections 再次查看数据库 mydb 中的集合:
> show tables
mycol
something
xixi
>
从结果中可以看出 mycol2 集合已被删除。
重命名集合
通过 db.collection1.renameCollection( " collection2" )重命名集合名。
> show tables
mycol
something
xixi
> db.xixi.renameCollection("haha")
{ "ok" : 1 }
> show tables
haha
mycol
something
>
MongoDB 文档增删改查
命令操作 | 作用 |
---|---|
db.collection.insert() | db.collection.insert()将单个文档或多个文档插入到集合 中 |
db.collection.insertOne() | 插入文档, 3.2 版中的新功能 |
db.collection.insertMany() | 插入多个文档,3.2 版中的新功能 |
db.collection.update | 更新或替换与指定过滤器匹配的单个文档,或更新与指 定 过 滤 器 匹 配 的 所 有 文 档 。 默 认 情 况 下 , db.collection.update()方法更新单个文档。 要更新多 个文档,请使用 multi 选项。 |
db.collection.updateOne( |
即使多个文档可能与指定的过滤器匹配,最多更新与指 定的过滤器匹配的单个文档。 3.2 版中的新功能 |
db.collection.updateMany( |
更新所有与指定过滤器匹配的文档。 3.2 版中的新功能 |
db.collection.replaceOne( |
即使多个文档可能与指定过滤器匹配,也最多替换一个 与指定过滤器匹配的文档。 |
db.collection.remove() | 删除单个文档或与指定过滤器匹配的所有文档 |
db.collection.deleteOne() | 即使多个文档可能与指定过滤器匹配,也最多删除一个 与指定过滤器匹配的文档。 3.2 版中的新功能 |
db.collection.deleteMany() | 删除所有与指定过滤器匹配的文档。 3.2 版中的新功能 |
db.collection.find(query, projection) | 查询文档 |
db.collection.findOne() |
常用查询操作符
比较操作符 | 描述 |
---|---|
$eq | 等值比较 |
$gt | 大于指定值 |
$gte | 大于或等于指定 值 |
$in | 数组中包含 |
$lt | 小于指定值 |
$lte | 小于或等于指定 值 |
$ne | 不等于指定值 |
$nin | 不在数组中包含 |
逻辑操作符 | 描述 |
---|---|
$and | "与"查询 |
$or | "或"查询 |
$not | "非"查询 |
$nor | "即非"查询 |
数组操作符 | 描述 |
---|---|
$all | 全包含 |
$elemMatch | 仅一个元素匹配 |
$size | 大小匹配 |
插入文档
MongoDB 使用 insert() 或 save() 方法向集合中插入文档,语法如下:
db.COLLECTION_NAME.insert(document)
或
db.COLLECTION_NAME.save(document)
- save():如果 _id 主键存在则更新数据,如果不存在就插入数据。该方法新版本中已废弃,可以使用 db.collection.insertOne() 或 db.collection.replaceOne() 来代替。
- insert(): 若插入的数据主键已经存在,则会抛 org.springframework.dao.DuplicateKeyException 异常,提示主键重复,不保存当前数据。
3.2 版本之后新增了 db.collection.insertOne() 和 db.collection.insertMany()。
db.collection.insertOne() 用于向集合插入一个新文档,语法格式如下:
db.collection.insertOne(
<document>,
{
writeConcern: <document>
}
)
db.collection.insertMany() 用于向集合插入一个多个文档,语法格式如下:
db.collection.insertMany(
[ <document 1> , <document 2>, ... ],
{
writeConcern: <document>,
ordered: <boolean>
}
)
参数说明:
- document:要写入的文档。
- writeConcern:写入策略,默认为 1,即要求确认写操作,0 是不要求。
- ordered:指定是否按顺序写入,默认 true,按顺序写入。
插入文档(1) - insert
db.houses.insert({
title: "海岸城商圈 城市印象家园 精装修两房 南二外",
tags: ["满五", "配套成熟"],
layout: "2室1厅1卫",
area: 74,
price:{
total: 7300000,
perMeter: 98648
},
publisher: "房似锦",
propertyRight: 70,
updateTime: new Date()
})
> db.houses.insert({
... title: "海岸城商圈 城市印象家园 精装修两房 南二外",
... tags: ["满五", "配套成熟"],
... layout: "2室1厅1卫",
... area: 74,
... price:{
... total: 7300000,
... perMeter: 98648
... },
... publisher: "房似锦",
... propertyRight: 70,
... updateTime: new Date()
... })
WriteResult({ "nInserted" : 1 })
>
插入文档(2) - insertOne
db.houses.insertOne({
title: "海岸城商圈 城市印象家园 精装修两房 南二外",
tags: ["满五", "配套成熟"],
layout: "2室1厅1卫",
area: 74,
price:{
total: 7300000,
perMeter: 98648
},
publisher: "房似锦",
propertyRight: 70,
updateTime: new Date()
})
> db.houses.insertOne({
... title: "海岸城商圈 城市印象家园 精装修两房 南二外",
... tags: ["满五", "配套成熟"],
... layout: "2室1厅1卫",
... area: 74,
... price:{
... total: 7300000,
... perMeter: 98648
... },
... publisher: "房似锦",
... propertyRight: 70,
... updateTime: new Date()
... })
{
"acknowledged" : true,
"insertedId" : ObjectId("623c95fe7ad87caadb5f3301")
}
>
插入文档(3) - insertMany
var hss = [];
hss.push({
title: "环中线地铁口景华岭肇送装修优选此套",
tags: ["满二", "学区房"],
layout: "3室1厅1卫",
area: 86,
publisher: "钟小天",
updateTime: new Date(),
price:{
total: 5300000,
perMeter: 98648
}
});
hss.push({
title: "海龙豪庭精装2房",
tags: ["满五唯一", "学区房"],
layout: "2室1厅1卫",
area: 66,
publisher: "钟小天",
updateTime: new Date(),
price:{
total: 7300000,
perMeter: 98648
}
});
db.houses.insertMany(hss);
> var hss = [];
> hss.push({
... title: "环中线地铁口景华岭肇送装修优选此套",
... tags: ["满二", "学区房"],
... layout: "3室1厅1卫",
... area: 86,
... publisher: "钟小天",
... updateTime: new Date(),
... price:{
... total: 5300000,
... perMeter: 98648
... }
... });
hss.push({
title: "海龙豪庭精装2房",
tags: ["满五唯一", "学区房"],
layout: "2室1厅1卫",
area: 66,
publisher: "钟小天",
updateTime: new Date(),
price:{
total: 7300000,
perMeter: 98648
}
});1
> hss.push({
... title: "海龙豪庭精装2房",
... tags: ["满五唯一", "学区房"],
... layout: "2室1厅1卫",
... area: 66,
... publisher: "钟小天",
... updateTime: new Date(),
... price:{
... total: 7300000,
... perMeter: 98648
... }
... });
2
> db.houses.insertMany(hss);
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("623c99347ad87caadb5f3303"),
ObjectId("623c99347ad87caadb5f3304")
]
}
>
查询文档
MongoDB 查询文档使用 find() 方法。
find() 方法以非结构化的方式来显示所有文档。
语法
MongoDB 查询数据的语法格式如下:
db.collection.find(query, projection)
- query :可选,使用查询操作符指定查询条件
- projection :可选,使用投影操作符指定返回的键。查询时返回文档中所有键值, 只需省略该参数即可(默认省略)。
如果你需要以易读的方式来读取数据,可以使用 pretty() 方法,语法格式如下:
>db.col.find().pretty()
pretty() 方法以格式化的方式来显示所有文档。
查询文档(1) - find
查询所有
db.houses.find()
> db.houses.find()
{ "_id" : ObjectId("623c95fe7ad87caadb5f3301"), "title" : "海岸城商圈 城市印象家园 精装修两房 南二外", "tags" : [ "满五", "配套成熟" ], "layout" : "2室1厅1卫", "area" : 74, "price" : { "total" : 7300000, "perMeter" : 98648 }, "publisher" : "房似锦", "propertyRight" : 70, "updateTime" : ISODate("2022-03-24T16:02:06.221Z") }
{ "_id" : ObjectId("623c964e7ad87caadb5f3302"), "title" : "海岸城商圈 城市印象家园 精装修两房 南二外", "tags" : [ "满五", "配套成熟" ], "layout" : "2室1厅1卫", "area" : 74, "price" : { "total" : 7300000, "perMeter" : 98648 }, "publisher" : "房似锦", "propertyRight" : 70, "updateTime" : ISODate("2022-03-24T16:03:26.810Z") }
{ "_id" : ObjectId("623c99347ad87caadb5f3303"), "title" : "环中线地铁口景华岭肇送装修优选此套", "tags" : [ "满二", "学区房" ], "layout" : "3室1厅1卫", "area" : 86, "publisher" : "钟小天", "updateTime" : ISODate("2022-03-24T16:15:36.987Z"), "price" : { "total" : 5300000, "perMeter" : 98648 } }
{ "_id" : ObjectId("623c99347ad87caadb5f3304"), "title" : "海龙豪庭精装2房", "tags" : [ "满五唯一", "学区房" ], "layout" : "2室1厅1卫", "area" : 66, "publisher" : "钟小天", "updateTime" : ISODate("2022-03-24T16:15:39.161Z"), "price" : { "total" : 7300000, "perMeter" : 98648 } }
>
db.houses.find().pretty()
> db.houses.find().pretty()
{
"_id" : ObjectId("623c95fe7ad87caadb5f3301"),
"title" : "海岸城商圈 城市印象家园 精装修两房 南二外",
"tags" : [
"满五",
"配套成熟"
],
"layout" : "2室1厅1卫",
"area" : 74,
"price" : {
"total" : 7300000,
"perMeter" : 98648
},
"publisher" : "房似锦",
"propertyRight" : 70,
"updateTime" : ISODate("2022-03-24T16:02:06.221Z")
}
{
"_id" : ObjectId("623c964e7ad87caadb5f3302"),
"title" : "海岸城商圈 城市印象家园 精装修两房 南二外",
"tags" : [
"满五",
"配套成熟"
],
"layout" : "2室1厅1卫",
"area" : 74,
"price" : {
"total" : 7300000,
"perMeter" : 98648
},
"publisher" : "房似锦",
"propertyRight" : 70,
"updateTime" : ISODate("2022-03-24T16:03:26.810Z")
}
{
"_id" : ObjectId("623c99347ad87caadb5f3303"),
"title" : "环中线地铁口景华岭肇送装修优选此套",
"tags" : [
"满二",
"学区房"
],
"layout" : "3室1厅1卫",
"area" : 86,
"publisher" : "钟小天",
"updateTime" : ISODate("2022-03-24T16:15:36.987Z"),
"price" : {
"total" : 5300000,
"perMeter" : 98648
}
}
{
"_id" : ObjectId("623c99347ad87caadb5f3304"),
"title" : "海龙豪庭精装2房",
"tags" : [
"满五唯一",
"学区房"
],
"layout" : "2室1厅1卫",
"area" : 66,
"publisher" : "钟小天",
"updateTime" : ISODate("2022-03-24T16:15:39.161Z"),
"price" : {
"total" : 7300000,
"perMeter" : 98648
}
}
>
查询文档(2) - find --按条件查询
查询price.total小于或者等于6000000的数据
db.houses.find({
"price.total": {
"$lte": 6000000
}
})
> db.houses.find({
... "price.total": {
... "$lte": 6000000
... }
... })
{ "_id" : ObjectId("623c99347ad87caadb5f3303"), "title" : "环中线地铁口景华岭肇送装修优选此套", "tags" : [ "满二", "学区房" ], "layout" : "3室1厅1卫", "area" : 86, "publisher" : "钟小天", "updateTime" : ISODate("2022-03-24T16:15:36.987Z"), "price" : { "total" : 5300000, "perMeter" : 98648 } }
>
按publishe查询
db.houses.find({
"publisher": "房似锦"
})
> db.houses.find({
... "publisher": "房似锦"
... })
{ "_id" : ObjectId("623c95fe7ad87caadb5f3301"), "title" : "海岸城商圈 城市印象家园 精装修两房 南二外", "tags" : [ "满五", "配套成熟" ], "layout" : "2室1厅1卫", "area" : 74, "price" : { "total" : 7300000, "perMeter" : 98648 }, "publisher" : "房似锦", "propertyRight" : 70, "updateTime" : ISODate("2022-03-24T16:02:06.221Z") }
{ "_id" : ObjectId("623c964e7ad87caadb5f3302"), "title" : "海岸城商圈 城市印象家园 精装修两房 南二外", "tags" : [ "满五", "配套成熟" ], "layout" : "2室1厅1卫", "area" : 74, "price" : { "total" : 7300000, "perMeter" : 98648 }, "publisher" : "房似锦", "propertyRight" : 70, "updateTime" : ISODate("2022-03-24T16:03:26.810Z") }
>
查询文档(3) - findOne
findOne 结果不唯一时,只会返回满足条件的第一个文档
db.houses.findOne({
_id: ObjectId("623c99347ad87caadb5f3303")
})
> db.houses.findOne({
... _id: ObjectId("623c99347ad87caadb5f3303")
... })
{
"_id" : ObjectId("623c99347ad87caadb5f3303"),
"title" : "环中线地铁口景华岭肇送装修优选此套",
"tags" : [
"满二",
"学区房"
],
"layout" : "3室1厅1卫",
"area" : 86,
"publisher" : "钟小天",
"updateTime" : ISODate("2022-03-24T16:15:36.987Z"),
"price" : {
"total" : 5300000,
"perMeter" : 98648
}
}
>
查询文档(4) – 分页
db.houses.find().skip(2).limit(10).sort({updateTime: -1})
- limit - 限定返回条目
- skip - 跳过指定条目
- sort - 按什么排序,其中 1 为升序排列,而 -1 是用于降序排列
> db.houses.find().skip(2).limit(10).sort({updateTime: -1})
{ "_id" : ObjectId("623c964e7ad87caadb5f3302"), "title" : "海岸城商圈 城市印象家园 精装修两房 南二外", "tags" : [ "满五", "配套成熟" ], "layout" : "2室1厅1卫", "area" : 74, "price" : { "total" : 7300000, "perMeter" : 98648 }, "publisher" : "房似锦", "propertyRight" : 70, "updateTime" : ISODate("2022-03-24T16:03:26.810Z") }
{ "_id" : ObjectId("623c95fe7ad87caadb5f3301"), "title" : "海岸城商圈 城市印象家园 精装修两房 南二外", "tags" : [ "满五", "配套成熟" ], "layout" : "2室1厅1卫", "area" : 74, "price" : { "total" : 7300000, "perMeter" : 98648 }, "publisher" : "房似锦", "propertyRight" : 70, "updateTime" : ISODate("2022-03-24T16:02:06.221Z") }
>
查询文档(5) – 使用projection指定返回字段
db.houses.find (
{"price.perMeter": { $lt: 100000} },
{publisher: 1, title: 1}
)
默认会返回ID字段
> db.houses.find (
... {"price.perMeter": { $lt: 100000} },
... {publisher: 1, title: 1}
... )
{ "_id" : ObjectId("623c95fe7ad87caadb5f3301"), "title" : "海岸城商圈 城市印象家园 精装修两房 南二外", "publisher" : "房似锦" }
{ "_id" : ObjectId("623c964e7ad87caadb5f3302"), "title" : "海岸城商圈 城市印象家园 精装修两房 南二外", "publisher" : "房似锦" }
{ "_id" : ObjectId("623c99347ad87caadb5f3303"), "title" : "环中线地铁口景华岭肇送装修优选此套", "publisher" : "钟小天" }
{ "_id" : ObjectId("623c99347ad87caadb5f3304"), "title" : "海龙豪庭精装2房", "publisher" : "钟小天" }
>
设置不返回ID字段
db.houses.find (
{"price.perMeter": { $lt: 100000} },
{publisher: 1, title: 1, _id: 0}
)
> db.houses.find (
... {"price.perMeter": { $lt: 100000} },
... {publisher: 1, title: 1, _id: 0}
... )
{ "title" : "海岸城商圈 城市印象家园 精装修两房 南二外", "publisher" : "房似锦" }
{ "title" : "海岸城商圈 城市印象家园 精装修两房 南二外", "publisher" : "房似锦" }
{ "title" : "环中线地铁口景华岭肇送装修优选此套", "publisher" : "钟小天" }
{ "title" : "海龙豪庭精装2房", "publisher" : "钟小天" }
>
更新文档
MongoDB 使用 update() 方法来更新集合中的文档。
update() 方法
update() 方法用于更新已存在的文档。语法格式如下:
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>
}
)
参数说明:
- query : update的查询条件,类似sql update查询内where后面的。
- update : update的对象和一些更新的操作符(如\(,\)inc...)等,也可以理解为sql update查询内set后面的
- upsert : 可选,这个参数的意思是,如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入。
- multi : 可选,mongodb 默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新。
- writeConcern :可选,抛出异常的级别。
更新文档(1) - update
db.houses.update(
{"_id" : ObjectId("623c95fe7ad87caadb5f3301")},
{
$set: {
"price.total": 7000000,
"price.perMeter": 94594,
"title": "(直降30万)海岸城 城市印象 精装修两房 南二外"
},
$push: {
"tags": "促销直降"
}
}
)
> db.houses.find ()
{ "_id" : ObjectId("623c95fe7ad87caadb5f3301"), "title" : "海岸城商圈 城市印象家园 精装修两房 南二外", "tags" : [ "满五", "配套成熟" ], "layout" : "2室1厅1卫", "area" : 74, "price" : { "total" : 7300000, "perMeter" : 98648 }, "publisher" : "房似锦", "propertyRight" : 70, "updateTime" : ISODate("2022-03-24T16:02:06.221Z") }
{ "_id" : ObjectId("623c964e7ad87caadb5f3302"), "title" : "海岸城商圈 城市印象家园 精装修两房 南二外", "tags" : [ "满五", "配套成熟" ], "layout" : "2室1厅1卫", "area" : 74, "price" : { "total" : 7300000, "perMeter" : 98648 }, "publisher" : "房似锦", "propertyRight" : 70, "updateTime" : ISODate("2022-03-24T16:03:26.810Z") }
{ "_id" : ObjectId("623c99347ad87caadb5f3303"), "title" : "环中线地铁口景华岭肇送装修优选此套", "tags" : [ "满二", "学区房" ], "layout" : "3室1厅1卫", "area" : 86, "publisher" : "钟小天", "updateTime" : ISODate("2022-03-24T16:15:36.987Z"), "price" : { "total" : 5300000, "perMeter" : 98648 } }
{ "_id" : ObjectId("623c99347ad87caadb5f3304"), "title" : "海龙豪庭精装2房", "tags" : [ "满五唯一", "学区房" ], "layout" : "2室1厅1卫", "area" : 66, "publisher" : "钟小天", "updateTime" : ISODate("2022-03-24T16:15:39.161Z"), "price" : { "total" : 7300000, "perMeter" : 98648 } }
> db.houses.update(
... {"_id" : ObjectId("623c95fe7ad87caadb5f3301")},
... {
... $set: {
... "price.total": 7000000,
... "price.perMeter": 94594,
... "title": "(直降30万)海岸城 城市印象 精装修两房 南二外"
... },
... $push: {
... "tags": "促销直降"
... }
... }
... )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.houses.find ()
{ "_id" : ObjectId("623c95fe7ad87caadb5f3301"), "title" : "(直降30万)海岸城 城市印象 精装修两房 南二外", "tags" : [ "满五", "配套成熟", "促销直降" ], "layout" : "2室1厅1卫", "area" : 74, "price" : { "total" : 7000000, "perMeter" : 94594 }, "publisher" : "房似锦", "propertyRight" : 70, "updateTime" : ISODate("2022-03-24T16:02:06.221Z") }
{ "_id" : ObjectId("623c964e7ad87caadb5f3302"), "title" : "海岸城商圈 城市印象家园 精装修两房 南二外", "tags" : [ "满五", "配套成熟" ], "layout" : "2室1厅1卫", "area" : 74, "price" : { "total" : 7300000, "perMeter" : 98648 }, "publisher" : "房似锦", "propertyRight" : 70, "updateTime" : ISODate("2022-03-24T16:03:26.810Z") }
{ "_id" : ObjectId("623c99347ad87caadb5f3303"), "title" : "环中线地铁口景华岭肇送装修优选此套", "tags" : [ "满二", "学区房" ], "layout" : "3室1厅1卫", "area" : 86, "publisher" : "钟小天", "updateTime" : ISODate("2022-03-24T16:15:36.987Z"), "price" : { "total" : 5300000, "perMeter" : 98648 } }
{ "_id" : ObjectId("623c99347ad87caadb5f3304"), "title" : "海龙豪庭精装2房", "tags" : [ "满五唯一", "学区房" ], "layout" : "2室1厅1卫", "area" : 66, "publisher" : "钟小天", "updateTime" : ISODate("2022-03-24T16:15:39.161Z"), "price" : { "total" : 7300000, "perMeter" : 98648 } }
>
更新文档(2) – update multi 更新多个文档
db.houses.update(
{"publisher" : "房似锦"},
{
$set: {
propertyRight: 40
}
},
{ multi: true}
)
> db.houses.update(
... {"publisher" : "房似锦"},
... {
... $set: {
... propertyRight: 40
... }
... },
... { multi: true}
... )
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
> db.houses.find()
{ "_id" : ObjectId("623c95fe7ad87caadb5f3301"), "title" : "(直降30万)海岸城 城市印象 精装修两房 南二外", "tags" : [ "满五", "配套成熟", "促销直降" ], "layout" : "2室1厅1卫", "area" : 74, "price" : { "total" : 7000000, "perMeter" : 94594 }, "publisher" : "房似锦", "propertyRight" : 40, "updateTime" : ISODate("2022-03-24T16:02:06.221Z") }
{ "_id" : ObjectId("623c964e7ad87caadb5f3302"), "title" : "海岸城商圈 城市印象家园 精装修两房 南二外", "tags" : [ "满五", "配套成熟" ], "layout" : "2室1厅1卫", "area" : 74, "price" : { "total" : 7300000, "perMeter" : 98648 }, "publisher" : "房似锦", "propertyRight" : 40, "updateTime" : ISODate("2022-03-24T16:03:26.810Z") }
{ "_id" : ObjectId("623c99347ad87caadb5f3303"), "title" : "环中线地铁口景华岭肇送装修优选此套", "tags" : [ "满二", "学区房" ], "layout" : "3室1厅1卫", "area" : 86, "publisher" : "钟小天", "updateTime" : ISODate("2022-03-24T16:15:36.987Z"), "price" : { "total" : 5300000, "perMeter" : 98648 } }
{ "_id" : ObjectId("623c99347ad87caadb5f3304"), "title" : "海龙豪庭精装2房", "tags" : [ "满五唯一", "学区房" ], "layout" : "2室1厅1卫", "area" : 66, "publisher" : "钟小天", "updateTime" : ISODate("2022-03-24T16:15:39.161Z"), "price" : { "total" : 7300000, "perMeter" : 98648 } }
>
更新文档(3) – pipeline(4.2版本)
db.houses.update(
{"_id":ObjectId("623c99347ad87caadb5f3304")},
[
{
$set:{"price.total":
{"$multiply":["$price.total", 0.9]}}
},
{
$set:{"price.perMeter":
{"$divide":["$price.total", "$area"]}}
},
]
)
> db.houses.find()
{ "_id" : ObjectId("623c95fe7ad87caadb5f3301"), "title" : "(直降30万)海岸城 城市印象 精装修两房 南二外", "tags" : [ "满五", "配套成熟", "促销直降" ], "layout" : "2室1厅1卫", "area" : 74, "price" : { "total" : 7000000, "perMeter" : 94594 }, "publisher" : "房似锦", "propertyRight" : 40, "updateTime" : ISODate("2022-03-24T16:02:06.221Z") }
{ "_id" : ObjectId("623c964e7ad87caadb5f3302"), "title" : "海岸城商圈 城市印象家园 精装修两房 南二外", "tags" : [ "满五", "配套成熟" ], "layout" : "2室1厅1卫", "area" : 74, "price" : { "total" : 7300000, "perMeter" : 98648 }, "publisher" : "房似锦", "propertyRight" : 40, "updateTime" : ISODate("2022-03-24T16:03:26.810Z") }
{ "_id" : ObjectId("623c99347ad87caadb5f3303"), "title" : "环中线地铁口景华岭肇送装修优选此套", "tags" : [ "满二", "学区房" ], "layout" : "3室1厅1卫", "area" : 86, "publisher" : "钟小天", "updateTime" : ISODate("2022-03-24T16:15:36.987Z"), "price" : { "total" : 5300000, "perMeter" : 98648 } }
{ "_id" : ObjectId("623c99347ad87caadb5f3304"), "title" : "海龙豪庭精装2房", "tags" : [ "满五唯一", "学区房" ], "layout" : "2室1厅1卫", "area" : 66, "publisher" : "钟小天", "updateTime" : ISODate("2022-03-24T16:15:39.161Z"), "price" : { "total" : 7300000, "perMeter" : 98648 } }
> db.houses.update(
... {"_id":ObjectId("623c99347ad87caadb5f3304")},
... [
... {
... $set:{"price.total":
... {"$multiply":["$price.total", 0.9]}}
... },
... {
... $set:{"price.perMeter":
... {"$divide":["$price.total", "$area"]}}
... },
... ]
... )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.houses.find()
{ "_id" : ObjectId("623c95fe7ad87caadb5f3301"), "title" : "(直降30万)海岸城 城市印象 精装修两房 南二外", "tags" : [ "满五", "配套成熟", "促销直降" ], "layout" : "2室1厅1卫", "area" : 74, "price" : { "total" : 7000000, "perMeter" : 94594 }, "publisher" : "房似锦", "propertyRight" : 40, "updateTime" : ISODate("2022-03-24T16:02:06.221Z") }
{ "_id" : ObjectId("623c964e7ad87caadb5f3302"), "title" : "海岸城商圈 城市印象家园 精装修两房 南二外", "tags" : [ "满五", "配套成熟" ], "layout" : "2室1厅1卫", "area" : 74, "price" : { "total" : 7300000, "perMeter" : 98648 }, "publisher" : "房似锦", "propertyRight" : 40, "updateTime" : ISODate("2022-03-24T16:03:26.810Z") }
{ "_id" : ObjectId("623c99347ad87caadb5f3303"), "title" : "环中线地铁口景华岭肇送装修优选此套", "tags" : [ "满二", "学区房" ], "layout" : "3室1厅1卫", "area" : 86, "publisher" : "钟小天", "updateTime" : ISODate("2022-03-24T16:15:36.987Z"), "price" : { "total" : 5300000, "perMeter" : 98648 } }
{ "_id" : ObjectId("623c99347ad87caadb5f3304"), "title" : "海龙豪庭精装2房", "tags" : [ "满五唯一", "学区房" ], "layout" : "2室1厅1卫", "area" : 66, "publisher" : "钟小天", "updateTime" : ISODate("2022-03-24T16:15:39.161Z"), "price" : { "total" : 6570000, "perMeter" : 99545.45454545454 } }
>
更新文档(4) – upsert 存在就更新,不存在就插入
db.agents.update(
{ phone: "15899019191" },
{
$set: {
"name": "房似锦",
"company": "安家天下",
"updateTime": new Date()
}
},
{
upsert: true
}
)
> db.agents.update(
... { phone: "15899019191" },
... {
... $set: {
... "name": "房似锦",
... "company": "安家天下",
... "updateTime": new Date()
... }
... },
... {
... upsert: true
... }
... )
WriteResult({
"nMatched" : 0,
"nUpserted" : 1,
"nModified" : 0,
"_id" : ObjectId("623ca819adcd5939e0e189cc")
})
> db.agents.find()
{ "_id" : ObjectId("623ca819adcd5939e0e189cc"), "phone" : "15899019191", "company" : "安家天下", "name" : "房似锦", "updateTime" : ISODate("2022-03-24T17:19:21.679Z") }
>
更新文档(5) – findAndModify 查询以及更新,会返回更新前的数据
db.agents.findAndModify(
{
"query":{ "phone": "15899019191" },
"update": {
$set: {
"creditLevel": "低",
"feedback": "相当差劲"
}
}
}
)
> db.agents.findAndModify(
... {
... "query":{ "phone": "15899019191" },
... "update": {
... $set: {
... "creditLevel": "低",
... "feedback": "相当差劲"
... }
... }
... }
... )
{
"_id" : ObjectId("623ca819adcd5939e0e189cc"),
"phone" : "15899019191",
"company" : "安家天下",
"name" : "房似锦",
"updateTime" : ISODate("2022-03-24T17:19:21.679Z")
}
>
更新文档(6) – findAndModify(new) 返回更新后的数据
db.agents.findAndModify(
{
"query":{ "phone": "15899019191" },
"update": {
$set: {
"creditLevel": "高",
"feedback": "好评如潮"
}
},
"new": true
}
)
> db.agents.findAndModify(
... {
... "query":{ "phone": "15899019191" },
... "update": {
... $set: {
... "creditLevel": "高",
... "feedback": "好评如潮"
... }
... },
... "new": true
... }
... )
{
"_id" : ObjectId("623ca819adcd5939e0e189cc"),
"phone" : "15899019191",
"company" : "安家天下",
"name" : "房似锦",
"updateTime" : ISODate("2022-03-24T17:19:21.679Z"),
"creditLevel" : "高",
"feedback" : "好评如潮"
}
>
findAndModify vs update
- findAndModify 仅支持单文档更新, update 支持多文档更新(指定multi)
- 在单文档更新场景下,两者都有原子性的保证。
- findAndModify 在条件满足多个文档时,可通过 sort 指定更新的文档。
- findAndModify 允许返回更新前、或更新后的文档,而 update 返回WriteResult
更新文档(7) - replace
先造个新数据
> db.orders.insert(
... {
... houseId: ObjectId("5ecc7c5c53378466dcbe25b3"),
... customer: "宫蓓蓓",
... agent: {
... name: "房似锦",
... company: "安家天下"
... },
... totalPrice: 7000000,
... createTime: new Date()
... } )
WriteResult({ "nInserted" : 1 })
> db.orders.find()
{ "_id" : ObjectId("623cab907ad87caadb5f3305"), "houseId" : ObjectId("5ecc7c5c53378466dcbe25b3"), "customer" : "宫蓓蓓", "agent" : { "name" : "房似锦", "company" : "安家天下" }, "totalPrice" : 7000000, "createTime" : ISODate("2022-03-24T17:34:08.311Z") }
>
db.orders.replaceOne(
{houseId: ObjectId("5ecc7c5c53378466dcbe25b3")},
{
houseId: ObjectId("5ecc7c5c53378466dcbe25b3"),
customer: "宫蓓蓓",
agent: {
name: "王子键"
},
totalPrice: 6800000,
createTime: new Date()
}
)
> db.orders.replaceOne(
... {houseId: ObjectId("5ecc7c5c53378466dcbe25b3")},
... {
... houseId: ObjectId("5ecc7c5c53378466dcbe25b3"),
... customer: "宫蓓蓓",
... agent: {
... name: "王子键"
... },
... totalPrice: 6800000,
... createTime: new Date()
... }
... )
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
> db.orders.find()
{ "_id" : ObjectId("623cab907ad87caadb5f3305"), "houseId" : ObjectId("5ecc7c5c53378466dcbe25b3"), "customer" : "宫蓓蓓", "agent" : { "name" : "王子键" }, "totalPrice" : 6800000, "createTime" : ISODate("2022-03-24T17:35:17.530Z") }
>
更新文档 – 语义函数
- update 更新指定条件的文档
- updateOne 更新指定条件的单个文档
- updateMany 更新指定条件的多个文档
- replaceOne 替换指定条件的单个文档
- findAndModify 更新指定条件的文档并返回
- findOneAndReplace 替换指定条件的文档并返回
- findOneAndUpdate 更新指定条件的单个文档并返回
删除文档
MongoDB remove() 函数是用来移除集合中的数据。
MongoDB 数据更新可以使用 update() 函数。在执行 remove() 函数前先执行 find() 命令来判断执行的条件是否正确,这是一个比较好的习惯。
语法
remove() 方法的基本语法格式如下所示:
db.collection.remove(
<query>,
{
justOne: <boolean>,
writeConcern: <document>
}
)
参数说明:
- query :(可选)删除的文档的条件。
- justOne : (可选)如果设为 true 或 1,则只删除一个文档,如果不设置该参数,或使用默认值 false,则删除所有匹配条件的文档。
- writeConcern :(可选)抛出异常的级别。
删除文档(1) - remove
db.houses.remove(
{
updateTime: {
$lt: new Date()
}
}
)
> db.houses.find()
{ "_id" : ObjectId("623c95fe7ad87caadb5f3301"), "title" : "(直降30万)海岸城 城市印象 精装修两房 南二外", "tags" : [ "满五", "配套成熟", "促销直降" ], "layout" : "2室1厅1卫", "area" : 74, "price" : { "total" : 7000000, "perMeter" : 94594 }, "publisher" : "房似锦", "propertyRight" : 40, "updateTime" : ISODate("2022-03-24T16:02:06.221Z") }
{ "_id" : ObjectId("623c964e7ad87caadb5f3302"), "title" : "海岸城商圈 城市印象家园 精装修两房 南二外", "tags" : [ "满五", "配套成熟" ], "layout" : "2室1厅1卫", "area" : 74, "price" : { "total" : 7300000, "perMeter" : 98648 }, "publisher" : "房似锦", "propertyRight" : 40, "updateTime" : ISODate("2022-03-24T16:03:26.810Z") }
{ "_id" : ObjectId("623c99347ad87caadb5f3303"), "title" : "环中线地铁口景华岭肇送装修优选此套", "tags" : [ "满二", "学区房" ], "layout" : "3室1厅1卫", "area" : 86, "publisher" : "钟小天", "updateTime" : ISODate("2022-03-24T16:15:36.987Z"), "price" : { "total" : 5300000, "perMeter" : 98648 } }
{ "_id" : ObjectId("623c99347ad87caadb5f3304"), "title" : "海龙豪庭精装2房", "tags" : [ "满五唯一", "学区房" ], "layout" : "2室1厅1卫", "area" : 66, "publisher" : "钟小天", "updateTime" : ISODate("2022-03-24T16:15:39.161Z"), "price" : { "total" : 6570000, "perMeter" : 99545.45454545454 } }
> db.houses.remove(
... {
... updateTime: {
... $lt: new Date()
... }
... }
... )
WriteResult({ "nRemoved" : 4 })
> db.houses.find()
>
删除文档(2) - drop
db.houses.drop()
drop 操作会清除整个集合,将文档、索引、元数据一并清除,执行效率比remove 更高。
> show tables
agents
houses
orders
> db.houses.drop()
true
> show tables
agents
orders
>
删除文档 – 语义函数
- remove 删除指定条件的文档
- deleteOne 删除指定条件的单个文档
- deleteMany 删除指定条件的多个文档
- findOneAndRemove 删除单个文档并返回