MongoDB 学习笔记之常用 shell 命令
常用 Mongo Shell
Switch Databse
查看当前的数据库
db
切换数据库
use examples
Popolate a collection(Insert)
MongoDB中的collections类似于关系型数据库中的tables,使用 db.collection.insertMany() 命令插入新的documents到collection中,如果当前没有collection MongoDB会新建它。
db.inventory.insertMany([
{ item: "journal", qty: 25, status: "A", size: { h: 14, w: 21, uom: "cm" }, tags: [ "blank", "red" ] },
{ item: "notebook", qty: 50, status: "A", size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "blank" ] },
{ item: "paper", qty: 10, status: "D", size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "blank", "plain" ] },
{ item: "planner", qty: 0, status: "D", size: { h: 22.85, w: 30, uom: "cm" }, tags: [ "blank", "red" ] },
{ item: "postcard", qty: 45, status: "A", size: { h: 10, w: 15.25, uom: "cm" }, tags: [ "blue" ] }
]);
// MongoDB adds an _id field with an ObjectId value if the field is not present in the document
Select All Documents
从collection中搜索documents可以使用 方法 db.collection.find()
返回所有的documents使用shell:
db.inventory.find({})
美化查询结果使用 .pretty()
db.inventory.find({}).pretty()
Specify Equality Matches
在collection中简单的查询示例
status等于“D”:
db.inventory.find({status:"D"});
qty等于0:
db.inventory.find({qty:0});
查询嵌套字段中的值:
db.inventory.find({"size.uom":"in"})
查询嵌套的字段下所有的值是否等于某值
db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )
返回字段下数组结构中是否包含某值
db.inventory.find( { tags: "red" } )
返回字段下数组结构中是否等于某段值
db.inventory.find( { tags: [ "red", "blank" ] } )
Specify Fields to Return(Projection)
选择需要返回的字段
db.inventory.find( {}, { _id: 0, item: 1, status: 1 } );
本作品采用《CC 协议》,转载必须注明作者和本文链接