一、创建操作
当我们在向集合中创建或者插入文档时,如果对应的集合不存在,mongodb 将自动创建。mongodb 提供以下方法插入文档:
db.collection.insertOne()
db.collection.insertMany()
提示
在 mongodb 中,如果操作对象是单个集合,所有的写入操作都是原子性的。
1.1 insertOne
db.inventory.insertOne(
{ item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
)
// 执行结果
{
acknowledged: true,
insertedId: ObjectId("63e1f308173bd1f61791536d")
}
db.inventory.find( { item: "canvas" } )
2.2 insertMany
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: {
'0': ObjectId("63e1f43c173bd1f61791536e"),
'1': ObjectId("63e1f43c173bd1f61791536f"),
'2': ObjectId("63e1f43c173bd1f617915370")
}
}
db.inventory.find( {} )
提示
如果集合当前不存在,则插入操作将 创建集合。
二、读取操作
mongodb 使用 db.collection.find()
方法从文档读取集合:
测试数据:
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" }
])
2.1 查询所有
db.inventory.find({})
// 类似:SELECT * FROM inventory
2.2 等于作为筛选条件
// {fielld1: <value1>, ...}
// db.inventory.find({ status: "D" })
// 类似:SELECT * FROM inventory WHERE status = "D"
2.3 查询运算符作为筛选条件
// { <field1>: { <operator1>: <value1> }, ... }
// db.inventory.find({ statue: { $in: ["A", "D"] } })
// 类似:SELECT * FROM inventory WHERE status in ("A", "D")
2.4 AND 筛选条件
// { status: "A", qty: { $lt: 30 } }
// SELECT * FROM inventory WHERE status = "A" AND qty < 30
2.5 OR 筛选条件
// { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] }
// SELECT * FROM inventory WHERE status = "A" OR qty < 30
2.6 AND 和 OR 筛选条件
// { status: "A", $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ] }
// SELECT * FROM inventory WHERE status = "A" AND ( qty < 30 OR item LIKE "p%")
提示
MongoDB 支持正则表达式 $regex
查询字符串。
2.7 针对嵌套文档查询
测试数据:
db.inventory.insertMany()
三、更新操作
db.collection.updateOne()
db.collection.updateMany()
db.collection.replaceOne()
前面是更新条件,后面是更新字段即值:
{
<update operator>: { <field1>: <value1>, ... },
<update operator>: { <field2>: <value2>, ... },
...
}
测试数据:
db.inventory.insertMany( [
{ item: "canvas", qty: 100, size: { h: 28, w: 35.5, uom: "cm" }, status: "A" },
{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "mat", qty: 85, size: { h: 27.9, w: 35.5, uom: "cm" }, status: "A" },
{ item: "mousepad", qty: 25, size: { h: 19, w: 22.85, uom: "cm" }, status: "P" },
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" },
{ 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" },
{ item: "sketchbook", qty: 80, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "sketch pad", qty: 95, size: { h: 22.85, w: 30.5, uom: "cm" }, status: "A" }
] );
// 更新当个
db.inventory.updateOne(
{ item: "paper" },
{
$set: { "size.uom": "cm", status: "P" },
$currentDate: { lastModified: true }
}
)
// 批量更新
db.inventory.updateMany(
{ "qty": { $lt: 50 } },
{
$set: { "size.uom": "in", status: "P" },
$currentDate: { lastModified: true }
}
)
// 替换文档
db.inventory.replaceOne(
{ item: "paper" },
{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40 } ] }
)
注意
使用 replaceOne()
只能替换整个文档,而 updateOne()
允许更新字段。
由于 replaceOne()
替换了整个文档,因此旧文档中没有包含在新文档中的字段将会丢失。使用 updateOne()
可以在不丢失旧文档中的字段的情况下添加新字段。
3.1 设置默认值
$replaceRoot
用输入文档替换指定文档,这操作将替换输入文档中的所有现有字段,包括字段。
{ $replaceRoot: { newRoot: <replacementDocument> } }
若我们要设置默认值,还得指定 $mergeObjects
来配合使用,意思合并文档后再替换原文档。
db.students2.updateMany({}, [
{
$replaceRoot: {
newRoot: {
$mergeObjects: [{ field1: 'default value1', ... }, "$$ROOT"]
}
}
},
{ $set: { modified: "$$NOW" } }
])
3.2 高级更新
这里将根据已有数据动态计算出成绩等级,并更新到文档。
db.students3.updateMany(
{ },
[
{ $set: { average : { $trunc: [ { $avg: "$tests" }, 0 ] }, modified: "$$NOW" } },
{ $set: { grade: { $switch: {
branches: [
{ case: { $gte: [ "$average", 90 ] }, then: "A" },
{ case: { $gte: [ "$average", 80 ] }, then: "B" },
{ case: { $gte: [ "$average", 70 ] }, then: "C" },
{ case: { $gte: [ "$average", 60 ] }, then: "D" }
],
default: "F"
} } } }
]
)
提示
若要使用变量,需要使用双引号括起来,例如:"$average"
四、删除操作
db.collection.deleteOne()
db.collection.deleteMany()
// { <field1>: <value1>, ... }
// { <field1>: { <operator1>: <value1> }, ... }
// 1、删除所有文档
db.inventory.deleteMany({})
// 2、指定条件
db.inventory.deleteMany({ status : "A" })
// 删除单个
db.inventory.deleteOne( { status: "D" } )
五、批量写入
db.collection.bulkWrite()
方法支持批量插入、更新、删除操作;
提示
批量插入还可以使用 db.collection.insertMany()
方法。
示例
try {
db.pizzas.bulkWrite( [
{ insertOne: { document: { _id: 3, type: "beef", size: "medium", price: 6 } } },
{ insertOne: { document: { _id: 4, type: "sausage", size: "large", price: 10 } } },
{ updateOne: {
filter: { type: "cheese" },
update: { $set: { price: 8 } }
} },
{ deleteOne: { filter: { type: "pepperoni"} } },
{ replaceOne: {
filter: { type: "vegan" },
replacement: { type: "tofu", size: "small", price: 4 }
} }
] )
} catch( error ) {
print( error )
}
结果:
{
acknowledged: true,
insertedCount: 2,
insertedIds: { '0': 3, '1': 4 },
matchedCount: 2,
modifiedCount: 2,
deletedCount: 1,
upsertedCount: 0,
upsertedIds: {}
}