操作格式:
示例:
db.fruit.insertOne({name: "apple"})
db.fruit.insertMany([
{name: "apple"},
{name: "pear"},
{name: "orange"},
])
关于 find :
find 示例:
db.movies.find({"year":1975}) // 单条件查询
db.movies.find({"year":1975, "title":"Batman"}) // 多条件and查询
db.movies.find({$and:[{"title":"Batman"},{"category":"action"}]}) // and的另一种形式
db.movies.find($or:[{"year":1987},{"title":"Batman"}]) // 多条件or查询
db.movies.find("title":/^B//) // 按正则表达式查找
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}} |
SQL | MQL |
---|---|
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]}} |
find 支持使用 “field.sub_field” 的形式查询子文档。假设有一个文档:
db.fruit.insertOne({
name: "apple",
from: {
country: "China",
province: "Guangdon"
}
})
考虑以下查询的意义:
// 我要查询from子文档country
db.fruit.find({"from.country": "China"})
// 我要查询from字段有一个country,country值为China
db.fruit.find({"from": {country: "China"}})
find 支持对数组中的元素进行搜索。假设有一个文档:
db.fruit.insert([
{"name": "Apple", color: ["red", "green"]},
{"name": "Mango", color: ["yello", "green"]}
])
考虑以下查询的意义:
// 查询color数组中有没有值为red
db.fruit.find({color: "red"})
// 查询color数组中值为red或者为yellow
db.fruit.find({$or: [{color: "red"}, {color: "yellow"}]})
插入下列文档,在其中搜索
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"
})
db.getCollection(‘movies‘).find([
"filming_locations": {
$elemMatch: {"city": "Rome", "country": "USA"}
}
])
// 不返回_id 返回title
db.movies.find({"category": "action"},{"_id":0, title:1})
以下示例:
// 删除a等于1的记录
db.testcol.remove({a: 1})
//删除a小于5的记录
db.testcol.remove({a: {$lt: 5}})
// 删除所有记录
db.testcol.remove({})
// 报错
db.testcol.remove()
Update 操作执行格式:db.<集合>.update(<查询条件>, <更新字段>)
举例:
// 插入一条数据
db.fruit.insertMany({
{name: "apple"},
{name: "pear"},
{name: "orange"}
})
// 查询name为apple的记录,将其form值修改为China
db.fruit.updateOne({name: "apple"}, {$set: {from: "China"}})
使用 updateOne
表示无论条件匹配多少条记录,始终只更新第一条;
使用 updateMany
表示条件匹配多少条就更新多少条;
updateOne
或者 updateMany
方法要求更新条件部分必须具有以下之一,否则将报错:
// 报错
db.fruit.updateOne({name: "apple"}, {from: "China"})
$push
:增加一个对象到数组底部$pushAll
:增加多个对象到数组底部$pop
:从数组底部删除一个对象$pull
:如果匹配指定的值,从数组中删除相应的对象$pullAll
:如果匹配任意的值,从数据中删除相应的对象$addToSet
:如果不存在则增加一个值到数组原文:https://www.cnblogs.com/niuben/p/14880970.html