MongoDB 启动和连接
使用 yum 安装, 相关目录如下:
- 默认端口号: 27017
- 日志文件: /var/log/mongodb/mongod.log
- 配置文件: /etc/mongod.conf
- 数据文件: /var/lib/mongo/
远程访问时, 需要将 mongod.conf 中的 bindIp 改为 0.0.0.0;
并且开放 mongo 的端口号, 直接在 /etc/firewalld/zones/public.xml 中添加<port protocol="tcp" port="27017">
启动:
service mongod start
停止
service mongod stop
重启
service mongod restart
创建连接:
mongo // 使用默认端口(27017)连接本地数据库
mongo --port 29019 // 使用自定义的端口连接本地数据库
mongo mongodb://192.168.239.132:27017 // 连接远程数据库
mongo --host 192.168.239.132 --port 27017
mongo --host mongodb://alice@mongodb0.examples.com:28015/?authSource=admin
mongo --username alice --password --authenticationDatabase admin --host mongodb0.examples.com --port 28015
显示当前数据库
db // 默认使用 test
切换数据库
use myNewDatabase
关闭:
// 方法一
quit()
// 方法二
use admin
db.shutdownServer()
Ctrl + C
数据库 CURD 操作
插入
- 在 mycollection 集合中插入一个文档
db.mycollection.insertOne()
- 在 mycollection 集合中插入一个集合
db.mycollection.insertMany()
- 在 mycollection 集合中插入一个文档或集合
db.mycollection.insert()
如:
db.inventory.insert(
[
{ 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.mycollection.find()
按条件查询
db.mycollection.find(
{ <field1>:<value1>, ... // 查找 field1 值为 value1 的文档 }
)
db.inventory.find( { status: "D" } )
嵌套字段查询
db.inventory.find(
{
"size.uom": "in"
}
)
使用查询运算符
mongodb 查询运算符
db.mycollection.find(
{ <field1>: { <operator1>: <value1> }, ... }
)
db.inventory.find( { status: { $in: [ "A", "D" ] } } )
AND 查询
db.inventory.find( { status: "A", qty: { $lt: 30 } } )
OR 查询
db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )
数组字段查询
db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
{ item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },
{ item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
{ item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
]);
- 数组完全匹配, 包括顺序且不能有其他元素
db.inventory.find( { tags: ["red","blank"] } )
// ["blank","red"] 字段查询不出
- 包含匹配, 不分顺序, 且可以有其它元素
db.inventory.find( { tags: "red" } ) // tags 中包含 red 的全部文档
db.inventory.find( { tags: { $all: ["red", "blank"] } } )
- 运算符匹配
db.mycollection.find( { <array field>: { <operator1>: <value1>, ... } } )
db.inventory.find( { dim_cm: { $gt: 25 } } ) // 查询 dim_cm 数组字段中至少有一个满足大于25的文档
db.inventory.find( { dim_cm: { $gt: 22, $lt: 30 } } ) // 查询 dim_cm 字段中元素有一个满足大于22且另一个元素小于30的文档, 或一个元素同时满足两个的文档
db.inventory.find( { dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } } } ) // 至少有一个元素满足所有条件
- 使用数组下标指定数组元素匹配
注: 使用数组下标时, 字段名必须写在引号内; 数组从0开始
db.inventory.find( { "dim_cm.1": { $gt: 25 } } ) // 查询 dim_cm 字段第二个元素大于25的文档
- 使用数组长度查询
db.inventory.find( { "tags": { $size: 3 } } ) // tags 长度为3的文档
嵌入式文档查询
db.inventory.insertMany( [
{ item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
{ item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] },
{ item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },
{ item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
]);
- 等式匹配
嵌套文档的等式匹配需要完全匹配, 包括顺序
db.inventory.find( { "instock": { warehouse: "A", qty: 5 } } )
// 该语句查询不到结果
db.inventory.find( { "instock": { qty: 5, warehouse: "A" } } )
- 指定嵌套在数组中的文档字段查询
db.inventory.find( { 'instock.qty': { $lte: 20 } } )
// 使用索引指定元素
db.inventory.find( { 'instock.0.qty': { $lte: 20 } } )
db.inventory.find( { "instock.qty": 5, "instock.warehouse": "A" } )
查询返回结果
通过设置字段为 1 或 0 确定是否返回该字段
返回指定字段
// 返回 item, status, _id 三个字段 (_id 默认返回)
db.inventory.find( { status: "A" }, { item: 1, status: 1 } )
// 返回 item, status
db.inventory.find( { status: "A" }, { item: 1, status: 1,_id: 0 } )
指定不返回字段
db.inventory.find( { status: "A" }, { status: 0, instock: 0 } )
包含嵌套文档的字段
指定嵌套字段返回
db.inventory.find(
{ status: "A" },
{ item: 1, status: 1, "size.uom": 1 }
)
指定数组元素返回
// 只能使用 $elemMatch, $slice, and $ 限定
// 返回最后一个元素
db.inventory.find( { status: "A" }, { item: 1, status: 1, instock: { $slice: -1 } } )
特殊查询 (null 或 字段不存在)
db.inventory.insertMany([
{ _id: 1, item: null },
{ _id: 2 }
])
直接使用 null 查询
// 以上两个文档都会查到
db.inventory.find( { item: null } )
类型查询 (null 的 BSON type 为10)
// 只能查询为 null 的文档
db.inventory.find( { item : { $type: 10 } } )
存在查询
// 查询不存在 item 字段的文档
db.inventory.find( { item : { $exists: false } } )
游标使用
db.mycollection.find() 方法返回一个游标, 需要使用该游标访问文档. 如果没有使用 var 赋值, mongo shell 默认自动迭代游标20次并且打印.
默认游标10分钟未活跃或全部迭代完后会别被关闭
手动使用游标如下:
var myCursor = db.users.find( { type: 2 } );
myCursor // 相当于默认调用
while (myCursor.hasNext()) {
print(tojson(myCursor.next())); // 以 json 格式打印全部
}
while (myCursor.hasNext()) {
printjson(myCursor.next()); // 同上
}
myCursor.forEach(printjson); // 使用 foreach 迭代全部, 并打印
var documentArray = myCursor.toArray(); // 转换为数组
var myDocument = documentArray[3];
var myCursor = db.users.find().noCursorTimeout(); // 关闭默认超时时间
myCursor.close() // 手动关闭游标
更新
_id 字段一旦确定, 不允许更新
更新一条文档
updateOne 更新满足条件的第一条文档
db.inventory.updateOne(
{ item: "paper" }, // 更新条件
{
$set: { "size.uom": "cm", status: "P" }, // $set 表示只更新部分字段
$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 } ] } // 没有 $set
)
update
update() 方法相当于前面三个方法. 其定义如下
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>, // 如果查询不存在, 是否创建新文档
multi: <boolean>, // 更新一个或多个
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ]
}
)
删除
删除全部
db.inventory.deleteMany({})
按条件删除多个
db.inventory.deleteMany({ status : "A" })
删除全部
db.inventory.deleteOne( { status: "D" } )