数据库
查看数据库
show dbs;
切换数据库(如果没有对应的数据库则创建)
use 数据库名;
删除当前数据库
db.dropDatabase();
集合
查看集合
show tables;
show collections;
创建集合
db.createCollection("集合名")
删除集合
db.集合名.drop();
文档
本例的集合名称为inventory
添加单个文档
db.集合.insertOne() (集合不存在会创建一个集合) (如果不指定id, MongoDB会使用ObjectId的value作为id)
db.inventory.insertOne( { item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } })
添加多个文档
db.集合.insertMany() (集合不存在会创建一个集合)
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" } ]);
查询集合所有文档
db.inventory.find({})
匹配有size: { h: 14, w: 21, uom: "cm" }内容的文档
db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )
匹配size中uom属性为“in”的文档
db.inventory.find( { "size.uom": "in" } )
匹配size中h属性值小于15的文档
db.inventory.find( { "size.h": { $lt: 15 } } )
匹配h属性小于15并且uom属性为“in”,并且“status”属性为"D"的文档
db.inventory.find( { "size.h": { $lt: 15 }, "size.uom": "in", status: "D" } )
删除集合所有文档
db.inventory.deleteMany({})
删除指定条件的文档
db.inventory.deleteMany({ status : "A" })
最多删除1个指定条件的文档
db.inventory.deleteOne( { status: "D" } )
插入下列文档,供更新操作
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" }] );
更新item值为“paper”的第一个文档 将它的size.uom设置为“cm”,status值设置为"P" 并且把lastModified字段更新为当前时间,如果该字段不存在,则生成一个
db.inventory.updateOne( { item: "paper" }, {$set: { "size.uom": "cm", status: "P" }, $currentDate: { lastModified: true }} )
更新qty属性值小于50的文档 将它的size.uom设置为“in”,status值设置为"P" 并且把lastModified字段更新为当前时间,如果该字段不存在,则生成一个
db.inventory.updateMany( { "qty": { $lt: 50 } }, { $set: { "size.uom": "in", status: "P" }, $currentDate: { lastModified: true } } )
把item属性为“paper”的文档替换成下面的内容
db.inventory.replaceOne( { item: "paper" },{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40 } ] })