MongoDB 6 安装
区别于MongoDB 4版本,MongoDB 6安装文件不包含客户端shell 连接工具,以及相应的管理工具,
如mongoimport、mongoexport 等工具。如需安装mongodb服务器、shell客户端、
管理工具则需要分三个部分分别安装。
喜欢绿色安装(不会由于疏漏 启动太多的服务),因此后续下载的安装文件都是压缩文件。
服务器安装
官方社区版下载地址
// 1. 解压压缩包
tar -zxvf mongodb-macos-x86_64-6.0.tgz
// 2. 在主目录创建数据目录
sudo mkdir -p /usr/local/var/mongodb
// 3. 创建主目录 日志文件目录
sudo mkdir -p /usr/local/var/log/mongodb
// 4. 在主目录下的bin目录下执行
./mongod --dbpath /usr/local/var/mongodb --logpath /usr/local/var/log/mongodb/mongo.log --fork
// 5. 指定配置文件启动
mongod --config /usr/local/etc/mongod.conf
// 6. mongodb 启动默认绑定27017端口 绑定ip为127.0.0.1,即只允许本机访问,可以通过如下方式让其他机器访问
// 6.1 启动行添加参数 --bind_ip
./mongod --dbpath /usr/local/var/mongodb --logpath /usr/local/var/log/mongodb/mongo.log --bind_ip 0.0.0.0 --fork
//6.2 配置文件
net:
bindIp: 0.0.0.0
客户端安装
官方客户端下载地址
// 下载解压后 在bin目录执行一下脚本
./mongosh --host 192.168.0.3
管理工具安装
提供数据导入、导出、系统监控等数据库运维管理工具。 官方下载地址
基本使用
数据库操作
// 显示数据库
test> show dbs
admin 40.00 KiB
config 60.00 KiB
local 72.00 KiB
/**
* 1. 创建/切换数据库 (数据库不存在时 直接创建并切换; 存在时 切换)
* 2. 此时 需要注意 使用 show dbs 并不能显示出来 crm数据库的相关信息
* 3. 在crm 数据库创建一个document,并插入一条记录 则立马显示数据库信息
*/
test> use crm
switched to db crm //创建并切换数据库到 crm
crm> show dbs
admin 40.00 KiB
config 72.00 KiB
local 72.00 KiB
// 在crm数据库中 执行以下脚本
db.movies.insertOne(
{
title: "The Favourite",
genres: [ "Drama", "History" ],
runtime: 121,
rated: "R",
year: 2018,
directors: [ "Yorgos Lanthimos" ],
cast: [ "Olivia Colman", "Emma Stone", "Rachel Weisz" ],
type: "movie"
}
)
// 执行 show dbs, 显示数据库信息
crm> show dbs
admin 40.00 KiB
config 108.00 KiB
crm 8.00 KiB
local 72.00 KiB
//删除collection
db.collection.drop()
CRUD
Insert
单行插入
crm> db.movies.insertOne(
... {
..... title: "The Favourite",
..... genres: [ "Drama", "History" ],
..... runtime: 121,
..... rated: "R",
..... year: 2018,
..... directors: [ "Yorgos Lanthimos" ],
..... cast: [ "Olivia Colman", "Emma Stone", "Rachel Weisz" ],
..... type: "movie"
..... }
... )
{
acknowledged: true,
insertedId: ObjectId("63306a9cf34b5e8ce7249258")
}
多行插入
db.movies.insertMany([
{
title: "Jurassic World: Fallen Kingdom",
genres: [ "Action", "Sci-Fi" ],
runtime: 130,
rated: "PG-13",
year: 2018,
directors: [ "J. A. Bayona" ],
cast: [ "Chris Pratt", "Bryce Dallas Howard", "Rafe Spall" ],
type: "movie"
},
{
title: "Tag",
genres: [ "Comedy", "Action" ],
runtime: 105,
rated: "R",
year: 2018,
directors: [ "Jeff Tomsic" ],
cast: [ "Annabelle Wallis", "Jeremy Renner", "Jon Hamm" ],
type: "movie"
}
])
批量插入
/*
* 基本语法; 按照指定顺序执行多个操作
* 1. operation 包含:insertOne、deleteOne、deleteMany、replaceOne、updateOne、updateMany
* 2. writeConcern : 可选项,跟事务相关,后续单独讲
* 3. ordered : 可选项 默认为true,服务端是否按顺序执行操作
*/
db.collection.bulkWrite(
[
{
writeConcern :
ordered :
}
)
// example 1 批量插入一条
db.movies.bulkWrite( [
{ insertOne : { "document" : {
title: "Jurassic World: Fallen Kingdom",
genres: [ "Action", "Sci-Fi" ],
runtime: 130,
rated: "PG-13",
year: 2018,
directors: [ "J. A. Bayona" ],
cast: [ "Chris Pratt", "Bryce Dallas Howard", "Rafe Spall" ],
type: "movie"
} } }
] )
/**
* 单行更新
* 根据过滤条件 更新单个文档;如果匹配多条数据,则更新第一条数据即可
*/
db.collection.bulkWrite( [
{ updateOne :
{
"filter":
"update":
"upsert":
"collation":
"arrayFilters": [
"hint":
}
}
] )
/**
* 多行更新
* 根据过滤条件 更新单个索引;如果匹配多条数据,则更新第一条数据即可
*/
db.collection.bulkWrite( [
{ updateOne :
{
"filter":
"update":
"upsert":
"collation":
"arrayFilters": [
"hint":
}
}
] )
/**
* 单文档替换
* 根据过滤条件替换单个文档,如果匹配多行,则替换第一个
*/
db.collection.bulkWrite([
{ replaceOne :
{
"filter" :
"replacement" :
"upsert" :
"collation":
"hint":
}
}
] )
/**
* 单文档删除
* 根据过滤条件删除单个文档,如果匹配多行,则删除第一个
*/
db.collection.bulkWrite([
{ deleteOne : {
"filter" :
"collation" :
} }
] )
/**
* 多文档删除
* 根据过滤条件删除所有符合条件文档
*/
db.collection.bulkWrite([
{ deleteMany: {
"filter" :
"collation" :
} }
] )
// example2
db.pizzas.bulkWrite( [
{ insertOne: { document: { _id: 3, type: "beef", size: "medium", price: 6 } } },
{ insertOne: { document: { _id: 4, type: "sausage", size: "large", price: 10 } } },
{ updateOne: {
filter: { type: "cheese" },
update: { $set: { price: 8 } }
} },
{ deleteOne: { filter: { type: "pepperoni"} } },
{ replaceOne: {
filter: { type: "vegan" },
replacement: { type: "tofu", size: "small", price: 4 }
} }
] )
//执行上面的脚本时,如果collection存在_id为4的文档,则报如下错误
writeErrors: [
WriteError {
err: {
index: 1,
code: 11000,
errmsg: 'E11000 duplicate key error collection: test.pizzas index: _id_ dup key: { _id: 4 }',
op: { _id: 4, type: 'sausage', size: 'large', price: 10 }
}
}
],
result: BulkWriteResult {
result: {
ok: 1,
writeErrors: [
WriteError {
err: {
index: 1,
code: 11000,
errmsg: 'E11000 duplicate key error collection: test.pizzas index: _id_ dup key: { _id: 4 }',
op: { _id: 4, type: 'sausage', size: 'large', price: 10 }
}
}
],
writeConcernErrors: [],
insertedIds: [ { index: 0, _id: 3 }, { index: 1, _id: 4 } ],
nInserted: 1,
nUpserted: 0,
nMatched: 0,
nModified: 0,
nRemoved: 0,
upserted: []
}
}
Query
基本查询 // 类似SQL中的 select * from table,查询所有数据
db.movies.find()
// 类似SQL中的 select * from table limit 2,限定返回数据
db.movies.find().limit(2)
// 类似SQL中的 select * from table limit 2,2,限定返回数据
db.movies.find().skip(2).limit(2)
// 类似SQL中的 select count(1) from table,查询总数
db.movies.count()
指定条件 // 类似SQL: SELECT * FROM table WHERE title = "Tag"
db.movies.find( { "title": "Tag" } )
// 范围查询 类似SQL: SELECT * FROM table WHERE rated in ("PG", "PG-13")
db.movies.find( { rated: { $in: [ "PG", "PG-13" ] } } )
// 逻辑比较 类似SQL: SELECT * FROM table WHERE countries = 'Mexico' and 'imdb.rating' >= 7
db.movies.find( { countries: "Mexico", "imdb.rating": { $gte: 7 } } )
// 逻辑比较 OR ; 查找年份为2010 或者 ( "awards.wins" 大于等于5 genres == "Drama" )
db.movies.find( {
year: 2010,
$or: [ { "awards.wins": { $gte: 5 } }, { genres: "Drama" } ]
} )
// 结果返回 指定字段, 1表示显示字段。 类似SQL: SELECT _id FROM table WHERE rated in ("PG", "PG-13")
db.movies.find( { rated: { $in: [ "PG", "PG-13" ] } },{_id:1} )
// 显示结果
[
{ _id: ObjectId("63306e72f34b5e8ce724925a") },
{ _id: ObjectId("63306e72f34b5e8ce724925c") },
{ _id: ObjectId("63306e72f34b5e8ce724925e") },
{ _id: ObjectId("63306e72f34b5e8ce7249260") },
{ _id: ObjectId("63306e72f34b5e8ce7249262") }
]
高级查询-内嵌文档查询 // 首先 插入测试数据 此时 size节点是一个JSON对象,即内嵌文档
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" }
]);
// query1 内嵌文档数据匹配
db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )
// 输出内容
[
{
_id: ObjectId("633072d4f34b5e8ce7249264"),
item: 'journal',
qty: 25,
size: { h: 14, w: 21, uom: 'cm' },
status: 'A'
}
]
// query2 内部字段查询; 可以将外部/内部的字段 通过.号 连接起来
db.inventory.find( { "size.uom": "in" } )
// 输出内容
[
{
_id: ObjectId("633072d4f34b5e8ce7249265"),
item: 'notebook',
qty: 50,
size: { h: 8.5, w: 11, uom: 'in' },
status: 'A'
},
{
_id: ObjectId("633072d4f34b5e8ce7249266"),
item: 'paper',
qty: 100,
size: { h: 8.5, w: 11, uom: 'in' },
status: 'D'
}
]
// query3 逻辑比较
db.inventory.find( { "size.h": { $lt: 15 } } )
// query4 条件 AND
db.inventory.find( { "size.h": { $lt: 15 }, "size.uom": "in", status: "D" } )
高级查询-数组查询 /*
* 1. 删除遗留测试数据
* 2. 插入测试数据
*/
db.inventory.drop();
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 ] }
]);
// query1 数组匹配 (精准匹配 条件出现的内容、位置、条数一摸一样才能被查询出来)
db.inventory.find( { tags: ["red", "blank"] } )
// query2 模糊匹配 (只需要数组中出现内容即可被查询出来)
db.inventory.find( { tags: { $all: ["red", "blank"] } } )
// query3 单元素查询
db.inventory.find( { tags: "red" } )
// query4 元素比较, 只需要任一元素 大于 25 即被查出
db.inventory.find( { dim_cm: { $gt: 25 } } )
// query5 多条件查询 数组元素需要大于15 或者 小于20
db.inventory.find( { dim_cm: { $gt: 15, $lt: 20 } } )
// query6 多条件查询 数组元素需要大于 22 且 小于30
db.inventory.find( { dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } } } )
// query7 数组下标查询 (下标从0开始),第二个元素大于25
db.inventory.find( { "dim_cm.1": { $gt: 25 } } )
// query8 数组长度查询, 查询数组长度为3的document
db.inventory.find( { "tags": { $size: 3 } } )
高级查询-数组内嵌文档查询 /*
* 1. 删除遗留测试数据
* 2. 插入测试数据
*/
db.inventory.drop();
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 } ] }
]);
// query1 根据数组内部文档查询
db.inventory.find( { "instock": { warehouse: "A", qty: 5 } } )
// query2 数组内嵌文档比较查询
db.inventory.find( { 'instock.qty': { $lte: 20 } } )
// query3 使用数组下标 比较查询
db.inventory.find( { 'instock.0.qty': { $lte: 20 } } )
// query4 数组匹配查询 (只要一个匹配就会被查询)
db.inventory.find( { "instock": { $elemMatch: { qty: 5, warehouse: "A" } } } )
// query5 数组逻辑比较查询
// 数组中的元素 > 10 and < 20; 一个满足就会被查询
db.inventory.find( { "instock": { $elemMatch: { qty: { $gt: 10, $lte: 20 } } } } )
// 数组中的元素 > 10 or < 20; 一个满足就会被查询; 小细节希望大家注意
db.inventory.find( { "instock.qty": { $gt: 10, $lte: 20 } } )
// query6 OR 关系; 只要数组中的数据满足其中一个条件即可
db.inventory.find( { "instock.qty": 5, "instock.warehouse": "A" } )
高级查询-指定返回字段 /*
* 1. 删除遗留测试数据
* 2. 插入测试数据
*/
db.inventory.drop();
db.inventory.insertMany( [
{ item: "journal", status: "A", size: { h: 14, w: 21, uom: "cm" }, instock: [ { warehouse: "A", qty: 5 } ] },
{ item: "notebook", status: "A", size: { h: 8.5, w: 11, uom: "in" }, instock: [ { warehouse: "C", qty: 5 } ] },
{ item: "paper", status: "D", size: { h: 8.5, w: 11, uom: "in" }, instock: [ { warehouse: "A", qty: 60 } ] },
{ item: "planner", status: "D", size: { h: 22.85, w: 30, uom: "cm" }, instock: [ { warehouse: "A", qty: 40 } ] },
{ item: "postcard", status: "A", size: { h: 10, w: 15.25, uom: "cm" }, instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
]);
// query1 查询状态为A的数据,返回所有字段
db.inventory.find( { status: "A" } )
// query2 mongodb 查询返回指定字段;_id 默认被返回
db.inventory.find( { status: "A" }, { item: 1, status: 1 } )
// query3 不返回_id
db.inventory.find( { status: "A" }, { item: 1, status: 1, _id: 0 } )
// query4 排除需要返回的字段
db.inventory.find( { status: "A" }, { status: 0, instock: 0 } )
// query5 返回内嵌文档的指定字段
db.inventory.find(
{ status: "A" },
{ item: 1, status: 1, "size.uom": 1 }
)
// query6 排除内嵌文档中的字段
db.inventory.find(
{ status: "A" },
{ "size.uom": 0 }
)
// query7 返回数组中的指定字段
db.inventory.find( { status: "A" }, { item: 1, status: 1, "instock.qty": 1 } )
// query8 返回数组中最后一个元素
db.inventory.find( { status: "A" }, { item: 1, status: 1, instock: { $slice: -1 } }
高级查询-null/缺失字段查询 /*
* 1. 删除遗留测试数据
* 2. 插入测试数据
*/
db.inventory.drop();
db.inventory.insertMany( [
{ "_id": 1 , "item": null },
{ "_id": 2 }
]);
// query1 查询为null的字段 (当字段不存在时 以下查询条件也满足)
db.inventory.find({item: null})
// query2 只返回null的数据 ($type为10表示Null)
db.inventory.find({"item": {$type : 10}})
// query3 查询字段不存在的数据
db.inventory.find({"item": {$exists: false}})
// query4 查询字段存在 且不为null的数据
db.inventory.find({"item": {"$ne": null, $exists: true}})
Update
// 单个更新
db.movies.updateOne( { title: "Tag" },
{
$set: {
plot: "One month every year, five highly competitive friends hit the ground running for a no-holds-barred game of tag"
},
$currentDate: { lastModified: true }
})
// 批量更新
db.movies.updateMany(
{ security_deposit: { $lt: 100 } },
{
$set: { security_deposit: 100, minimum_nights: 1 }
}
)
// 替换
db.movies.replaceOne(
{ account_id: 371138 },
{ account_id: 893421, limit: 5000, products: [ "Investment", "Brokerage" ] }
)
Delete
// 删除所有数据
db.movies.deleteMany({})
// 指定条件删除
db.movies.deleteMany( { title: "Titanic" } )
// 仅删除一个 根据匹配条件
db.movies.deleteOne( { cast: "Brad Pitt" } )
好文阅读
发表评论