# MongoDB 基本操作
# 条件对照表
SQL | MQL |
---|---|
a = 1 | {a: 1} |
a <> 1 | {a: {$ne: 1}} |
a > 1 | {a: {$gt: 1}} |
a >= 1 | {a: {$gte: 1}} |
a < 1 | {a: {$lt: 1}} |
a <= 1 | {a: {$lte: 1}} |
a = 1 AND b = 1 | {a: 1, b: 1}或{$and: [{a: 1}, {b: 1}]} |
a = 1 OR b = 1 | {$or: [{a: 1}, {b: 1}]} |
a IS NULL | {a: {$exists: false}} |
a IN (1, 2, 3) | {a: {$in: [1, 2, 3]}} |
# 逻辑运算符
- $lt: 存在并小于
- $lte: 存在并小于等于
- $gt: 存在并大于
- $gte: 存在并大于等于
- $ne: 不存在或存在但不等于
- $in: 存在并在指定数组中
- $nin: 不存在或不在指定数组中
- $or: 匹配两个或多个条件中的一个
- $and: 匹配全部条件
# 使用 insert 插入数据
操作格式:
db.<集合>.insertOne(<JSON对象>)
db.getCollection('集合')..insertOne(<JSON对象>)
db.<集合>.insertMany([<JSON 1>, <JSON 2>, …<JSON n>])
db.getCollection('集合')..insertMany([<JSON 1>, <JSON 2>, …<JSON n>])
示例:
# 插入一条数据
db.fruit.insertOne({name: "apple"})
# 批量插入多条数据
db.fruit.insertMany([
{name: "apple"},
{name: "pear"},
{name: "orange"}
])
# 使用 find 查询文档
关于 find:
- find 是 MongoDB 中查询数据的基本指令,相当于 SQL 中的
SELECT
。 - find 返回的是游标。
find 示例:
db.movies.find( { "year" : 1975 } ) // 单条件查询
db.movies.find( { "year" : 1989, "title" : "Batman" } ) // 多条件 and 查询
db.movies.find( { $and : [ {"title" : "Batman"}, { "category" : "action" }] } ) // and 的另一种形式
db.movies.find( { $or: [{"year" : 1989}, {"title" : "Batman"}] } ) // 多条件 or 查询
db.movies.find( { "title" : /^B/} ) // 按正则表达式查找
# 使用 find 搜索子文档
find
支持使用 field.sub_field
的形式查询子文档。假设有一个文档:
db.fruit.insertOne({
name: "apple",
from: {
country: "China",
province: "Guangdon"
}
})
执行 db.fruit.find({"from.country":"China"})
可以查询到上面插入的数据。
执行 db.fruit.find({"from":{"country":"China"}})
,该查询语句意思是:查询 from
等于 {"country":"China"}
的数据,不能查询到上面插入的数据。
执行 db.fruit.find({"from":{"country":"China","province":"Guangdon"}})
可以查询到上面插入的数据。
# 使用 find 搜索数组
find
支持对数组中的元素进行搜索。假设有一个文档:
db.fruit.insert([
{ "name" : "Apple", color: ["red", "green" ] },
{ "name" : "Mango", color: ["yellow", "green"] }
])
执行 db.fruit.find({$or: [{color: "red"}, {color: "yellow"}]} )
,可以获得下面的数据:
{ "_id" : ObjectId("5ef356757c530654f5c38712"), "name" : "Apple", "color" : [ "red", "green" ] }
{ "_id" : ObjectId("5ef356757c530654f5c38713"), "name" : "Mango", "color" : [ "yellow", "green" ] }
# 使用 find 搜索数组中的对象
假设有一个文档:
db.movies.insertOne( {
"title" : "Raiders of the Lost Ark",
"filming_locations" : [
{ "city" : "Los Angeles", "state" : "CA", "country" :"USA" },
{ "city" : "Rome", "state" : "Lazio", "country" : "Italy" },
{ "city" : "Florence", "state" : "SC", "country" : "USA" }
]
})
查找城市是 Rome 的记录:
db.movies.find({"filming_locations.city": "Rome"})
在数组中搜索子对象的多个字段时,如果使用 $elemMatch
,它表示必须是 同一个子对象满足多个条件
。考虑以下两个查询:
db.getCollection('movies').find({
"filming_locations.city": "Rome",
"filming_locations.country": "USA"
})
上面的查询,会返回如下的结果:
{ "_id" : ObjectId("5ef359127c530654f5c38714"), "title" :
"Raiders of the Lost Ark", "filming_locations" : [ { "city" : "Los Angeles", "state" : "CA", "country" : "USA" }, {
"city" : "Rome", "state" : "Lazio", "country" : "Italy" }, { "city" : "Florence", "state" : "SC", "country" : "USA"
} ] }
如果指定多个查询条件时没有使用 $elemMatch
操作符,那么数组元素的组合(不一定是单一元素)必须满足所有条件;例如,数组中的不同元素可以满足条件的不同部分。
使用 elemMatch
进行查询:
db.getCollection('movies').find({
"filming_locations": {
$elemMatch:{"city":"Rome", "country": "USA"}
}
})
上面的查询,没有返回数据。说明使用 $elemMatch
,它表示必须是 同一个子对象满足多个条件
。
注意 filming_locations
必须是数组。
# 控制 find 返回的字段
find
可以指定只返回指定的字段;_id
字段必须明确指明不返回,否则默认返回;- 在 MongoDB 中我们称这为
投影(projection)
;
执行 db.movies.find({},{"_id":0, title:1})
会获得下面的数据:
{ "title" : "Raiders of the Lost Ark" }
如果没有过滤字段,则执行 db.movies.find({}).pretty()
会获得下面的数据:
{
"_id" : ObjectId("5ef359127c530654f5c38714"),
"title" : "Raiders of the Lost Ark",
"filming_locations" : [
{
"city" : "Los Angeles",
"state" : "CA",
"country" : "USA"
},
{
"city" : "Rome",
"state" : "Lazio",
"country" : "Italy"
},
{
"city" : "Florence",
"state" : "SC",
"country" : "USA"
}
]
}
pretty
会对返回结果,进行格式化处理。
# 使用 remove 删除文档
- remove 命令需要配合查询条件使用;
- 匹配查询条件的的文档会被删除;
- 指定一个空文档条件会删除所有文档;
db.testcol.remove( { a : 1 } ) // 删除a 等于1的记录
db.testcol.remove( { a : { $lt : 5 } } ) // 删除a 小于5的记录
db.testcol.remove( { } ) // 删除所有记录
db.testcol.remove() //报错
# 使用 update 更新文档
Update
操作执行格式:db.<集合>.update(<查询条件>, <更新字段>)
以以下数据为例:
db.fruit.insertMany([
{name: "apple"},
{name: "pear"},
{name: "orange"}
])
db.fruit.updateOne({name: "apple"}, {$set: {from: "China"}})
查询 name
为 apple
的记录,将找到记录的 from
设置为 China
。
{
"_id" : ObjectId("5ef365de7c530654f5c38718"),
"name" : "apple",
"from" : "China"
}
{ "_id" : ObjectId("5ef365de7c530654f5c38719"), "name" : "pear" }
{ "_id" : ObjectId("5ef365de7c530654f5c3871a"), "name" : "orange" }
- 使用
update
默认情况下, 只更新 一个 文档。要更新多个文档,请使用 multi 选项。; - 使用
updateOne
表示无论条件匹配多少条记录,始终只更新第一条; - 使用
updateMany
表示条件匹配多少条就更新多少条; updateOne/updateMany
方法要求更新条件部分必须具有以下操作符之一,否则将报错:$set
/$unset
$push
/$pushAll
/$pop
$pull
/$pullAll
$addToSet
# 操作符
$push
: 增加一个对象到数组底部$pushAll
: 增加多个对象到数组底部$pop
: 从数组底部删除一个对象$pull
: 如果匹配指定的值,从数组中删除相应的对象$pullAll
: 如果匹配任意的值,从数据中删除多个相应的对象$addToSet
: 如果不存在则增加一个值到数组
# 使用 drop 删除集合
删除一个集合:db.<集合>.drop()
- 集合中的全部文档都会被删除
- 集合相关的索引也会被删除
# 使用 dropDatabase 删除数据库
使用 db.dropDatabase()
来删除数据库
数据库相应文件也会被删除,磁盘空间将被释放
db.colToBeDropped.drop()
use tempDB
db.dropDatabase()
show collections // No collections
show dbs // The db is gone