1、Insert操作详解
插入一个文档
db.collection.insertOne()
db.inventory.insertOne(
{ item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
)
插入多个文档
db.collection.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" } }
])
db.collection.insert()
db.collection.insert(
<document or array of documents>,
{
writeConcern: <document>,
ordered: <boolean>
}
)
2、Query操作详解
查询所有
db.collection.find()
相当于:SELECT * FROM table_name
按条件查询
db.collection.find({ke:value})
相当于SELECT * FROM table_name WHERE name = ?
使用查询运算符指定条件
db.inventory.find( { status: { $in: [ "A", "D" ] } } )
相当于
SELECT * FROM inventory WHERE status in ("A", "D")
指定AND条件查询
less than ($lt)
db.inventory.find( { status: "A", qty: { $lt: 30 } } )
相当于
SELECT * FROM inventory WHERE status = "A" AND qty < 30
指定OR条件
db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )
相当于
SELECT * FROM inventory WHERE status = “A” OR qty < 30
指定AND和OR条件
db.inventory.find( {
status: "A",
$or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]
} )
相当于
SELECT * FROM inventory WHERE status = “A” AND ( qty < 30 OR item LIKE “p%” )
3、Update操作详解
更新单个文档db.collection.updateOne()
db.inventory.updateOne(
{ item: "paper" },
{
$set: { "size.uom": "cm", status: "P" },
$currentDate: { lastModified: true }
}
)
更新多个文档db.collection.updateMany()
db.inventory.updateMany(
{ "qty": { $lt: 50 } },
{
$set: { "size.uom": "in", status: "P" },
$currentDate: { lastModified: true }
}
)
替换文档db.collection.replaceOne()
db.inventory.replaceOne(
{ item: "paper" },
{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40 } ] }
)
4、Delete操作详解
删除所有文档db.collection.deleteMany()
db.inventory.deleteMany({})
删除与条件匹配的文档
db.inventory.deleteMany({ status : "A" })
删除与条件匹配的一个文档
db.inventory.deleteOne( { status: "D" } )