mongodb增删查改
document定义
关系型数据库的一条记录可以认为是一行.mongodb是非关系型数据库,它的一条记录是一个"文档"(document).mongodb的document是key-value结构的集合.
插入document
一次插入一个document
db.users.insertOne(
{
name: "sue",
age:26,
status:"pending"
}
)
db代表当前数据库,users是一个collection, 3个key-value的结构组成一个document.
一次插入多个document:
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" }
]);
查找document
要想查找collection中的所有数据,执行
db.inventory.find( {} )
查找status为D的document:
db.inventory.find( { status: "D" } )
查找status为D或者A的document:
db.inventory.find( { status: { $in: [ "A", "D" ] } } )
查找status为A且qty小于30的document:
db.inventory.find( { status: "A", qty: { $lt: 30 } } )
其中$lt是小于(less than)的意思.
查找status为A或者qty小于30的document:
db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )
更新document
把item为journal的document,size.uom修改为om,status修改为P.
db.inventory.updateOne(
{ item: "journal" },
{
$set: { "size.uom": "om", status: "P" }
}
)
更新多条记录
db.inventory.updateMany(
{ "qty": { $lt: 50 } },
{
$set: { "size.uom": "in", status: "P" },
$currentDate: { lastModified: true }
}
)
更新qty小于50的document的size.uom和status.
替换整个文档:
db.inventory.replaceOne(
{ item: "paper" },
{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40 } ] }
)
删除document
删除所有document:
db.inventory.deleteMany({})
删除status为A的document:
db.inventory.deleteMany({ status : "A" })
限制mongo占用内存大小
mongod --dbpath=/data/mongodb/ --rest --fork --logpath=/data/mongodb/mongo.log --logappend --wiredTigerCacheSizeGB 10
只安装客户端
在/etc/yum.repos.d/mongodb-org-4.0.repo里添加
[mongodb-org-4.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-4.0.asc
然后
yum install mongodb-org-shell