MongoDB安装、基础操作和聚合实例详解

虽然MongoDB这些年很流行,但笔者之前没研究过,现在有需求研究这类NoSQL的数据库,是为了验证其是否可被替换。

MongoDB是很轻量的文档数据库,简单测试也懒得专门准备虚拟机环境了,直接在macOS上安装测试下其基础功能。

  • 1.使用 Homebrew 安装 MongoDB
  • 2.启动/停止 MongoDB 服务
  • 3.启动 MongoDB Shell
  • 4.体验 MongoDB 基本操作
  • 5.体验 MongoDB 聚合操作

1. 使用 Homebrew 安装 MongoDB

复制代码
# 添加 MongoDB 存储库
brew tap mongodb/brew

# 安装 MongoDB 社区版
brew install mongodb-community

2. 启动/停止 MongoDB 服务

复制代码
# 启动 MongoDB 服务
brew services start mongodb/brew/mongodb-community

# 停止 MongoDB 服务(这个当然要等我们体验测试完成后才停..)
brew services stop mongodb/brew/mongodb-community

3. 启动 MongoDB Shell

复制代码
# 打开 MongoDB 的交互式 Shell
mongosh

在mongosh登录到MongoDB时可以看到,笔者这里安装的是7.0.12版本的MongoDB,使用默认端口27017:

复制代码
jingyuzhao@jingyuzhao-mac ~ % mongosh
Current Mongosh Log ID:	668ce3d3012a1d349d3a46b3
Connecting to:		mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.2.10
Using MongoDB:		7.0.12
Using Mongosh:		2.2.10

For mongosh info see: https://docs.mongodb.com/mongodb-shell/

------
   The server generated these startup warnings when booting
   2024-07-09T15:09:54.021+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
------

test> 

4. 体验MongoDB基本操作

下面进行一些基本的 MongoDB 操作示例:

1)创建数据库和集合:

复制代码
-- 切换到要使用的数据库(如果不存在则会自动创建)
use mydb

-- 创建集合
db.createCollection("myCollection")

2)插入文档:

复制代码
-- 插入单个文档:
db.myCollection.insertOne({ name: "Alfred", age: 34 })

-- 插入多个文档:
db.myCollection.insertMany([
  { name: "Mcdull", age: 33 },
  { name: "Sally", age: 4 }
])

3)查询文档:

复制代码
-- 查询所有文档:
db.myCollection.find()

-- 查询满足条件的文档:
db.myCollection.find({ age: { $gt: 25 } })

4)更新文档:

复制代码
-- 更新单个文档:
db.myCollection.updateOne({ name: "Alfred" }, { $set: { age: 29 } })

-- 更新多个文档:
db.myCollection.updateMany({ age: { $lt: 35 } }, { $set: { status: "Active" } })

5)删除文档:

复制代码
-- 删除单个文档,name值为'Sally'的记录:
db.myCollection.deleteOne({ name: "Sally" })

-- 删除多个文档,status值为'Active'的记录:
db.myCollection.deleteMany({ status: "Active" })

5. 体验MongoDB聚合操作

1)创建测试用例

复制代码
-- 删除 sales 集合
db.sales.drop()

-- 创建 sales 集合并插入示例文档
db.sales.insertMany([
  {
    "order_id": 1001,
    "product": "Laptop",
    "quantity": 2,
    "unit_price": 1200,
    "customer": "Alice",
    "order_date": ISODate("2024-06-07T08:30:00Z")
  },
  {
    "order_id": 1002,
    "product": "Monitor",
    "quantity": 1,
    "unit_price": 500,
    "customer": "Bob",
    "order_date": ISODate("2024-06-10T10:15:00Z")
  },
  {
    "order_id": 1003,
    "product": "Keyboard",
    "quantity": 3,
    "unit_price": 50,
    "customer": "Alice",
    "order_date": ISODate("2024-06-15T14:45:00Z")
  },
  {
    "order_id": 1004,
    "product": "Mouse",
    "quantity": 5,
    "unit_price": 20,
    "customer": "Charlie",
    "order_date": ISODate("2024-07-09T09:30:00Z")
  }
])

查询这个集合结果:

db.sales.find()

复制代码
mydb> db.sales.find()
[
  {
    _id: ObjectId('668cf766749a72317b175646'),
    order_id: 1001,
    product: 'Laptop',
    quantity: 2,
    unit_price: 1200,
    customer: 'Alice',
    order_date: ISODate('2024-06-07T08:30:00.000Z')
  },
  {
    _id: ObjectId('668cf766749a72317b175647'),
    order_id: 1002,
    product: 'Monitor',
    quantity: 1,
    unit_price: 500,
    customer: 'Bob',
    order_date: ISODate('2024-06-10T10:15:00.000Z')
  },
  {
    _id: ObjectId('668cf766749a72317b175648'),
    order_id: 1003,
    product: 'Keyboard',
    quantity: 3,
    unit_price: 50,
    customer: 'Alice',
    order_date: ISODate('2024-06-15T14:45:00.000Z')
  },
  {
    _id: ObjectId('668cf766749a72317b175649'),
    order_id: 1004,
    product: 'Mouse',
    quantity: 5,
    unit_price: 20,
    customer: 'Charlie',
    order_date: ISODate('2024-07-09T09:30:00.000Z')
  }
]
mydb> 

2)执行聚合操作

示例 1: 计算每个客户的总销售额和订单数量

复制代码
db.sales.aggregate([
  {
    $group: {
      _id: "$customer",
      totalSales: { $sum: { $multiply: ["$quantity", "$unit_price"] } },
      totalOrders: { $sum: 1 }
    }
  },
  { $sort: { totalSales: -1 } } // 按总销售额降序排序
])

查询结果:【计算每个客户的总销售额和订单数量】

复制代码
[
  { _id: 'Alice', totalSales: 2550, totalOrders: 2 },
  { _id: 'Bob', totalSales: 500, totalOrders: 1 },
  { _id: 'Charlie', totalSales: 100, totalOrders: 1 }
]

示例 2: 查找每种产品的平均销售价格和销售数量

复制代码
db.sales.aggregate([
  {
    $group: {
      _id: "$product",
      avgPrice: { $avg: "$unit_price" },
      totalQuantity: { $sum: "$quantity" }
    }
  },
  { $sort: { _id: 1 } } // 按产品名称升序排序
])

查询结果:【查找每种产品的平均销售价格和销售数量】

复制代码
[
  { _id: 'Keyboard', avgPrice: 50, totalQuantity: 3 },
  { _id: 'Laptop', avgPrice: 1200, totalQuantity: 2 },
  { _id: 'Monitor', avgPrice: 500, totalQuantity: 1 },
  { _id: 'Mouse', avgPrice: 20, totalQuantity: 5 }
]

示例 3: 筛选特定日期范围内的销售订单并投影字段

复制代码
db.sales.aggregate([
  {
    $match: {
      order_date: {
        $gte: ISODate("2024-06-01"),
        $lte: ISODate("2024-06-30")
      }
    }
  },
  {
    $project: {
      order_id: 1,
      product: 1,
      quantity: 1,
      totalAmount: { $multiply: ["$quantity", "$unit_price"] }
    }
  }
])

查询结果:【筛选特定日期范围内的销售订单并投影字段】

复制代码
[
  {
    _id: ObjectId('668cf766749a72317b175646'),
    order_id: 1001,
    product: 'Laptop',
    quantity: 2,
    totalAmount: 2400
  },
  {
    _id: ObjectId('668cf766749a72317b175647'),
    order_id: 1002,
    product: 'Monitor',
    quantity: 1,
    totalAmount: 500
  },
  {
    _id: ObjectId('668cf766749a72317b175648'),
    order_id: 1003,
    product: 'Keyboard',
    quantity: 3,
    totalAmount: 150
  }
]

至此,我们学习了如何安装、启动和停止 MongoDB,并通过 MongoDB Shell 执行基础的 CRUD 操作(创建、查询、更新和删除文档),同时探索了 MongoDB 的聚合操作,用于实现复杂的数据分析。后续,会继续研究关于Oracle 23ai在JSON这方面的能力表现。

相关推荐
杨云龙UP6 小时前
Docker 部署 MongoDB 6.0 数据库每日自动备份实践:本地 + 异地保留 7 天_20260429
linux·运维·数据库·mongodb·docker·容器·centos
稳联技术老娜21 小时前
Profinet转EtherCAT网关通讯架构及EtherCAT超距故障解决原理
mongodb
别来无恙blwy2 天前
windows MongoDB升级-自动升级脚本-自动检测升级到任意版本
数据库·windows·mongodb
snow@li2 天前
数据库-MongoDB:常用语法 / MongoDB 核心知识技能梳理
数据库·mongodb
刘晨鑫16 天前
MongoDB数据库应用
数据库·mongodb
爬山算法6 天前
MongoDB(92)什么是变更流(Change Streams)?
数据库·mongodb
小冯不疯6 天前
旺店通与金蝶云星空入库单管理对接方案
mongodb
MongoDB 数据平台7 天前
为编码代理引入 MongoDB 代理技能和插件
数据库·mongodb
忍冬行者7 天前
MongoDB 三节点副本集离线部署运维手册
运维·数据库·mongodb
卢傢蕊8 天前
MongoDB
数据库·mongodb