MongoDB系列:管道操作:聚合阶段操作符(二)

MongoDB系列:管道操作:聚合阶段操作符(二)

聚合阶段操作符介绍

本节只编写了个人认为可能用到的操作符,详细更多的操作符以及使用注意事项请前往MongoDB官网

$match

过滤匹配数据。

// 插入数据
db.orders.insertMany( [
  {
    "_id" : 1, "item" : "almonds", "price" : 12, "ordered" : 2 },
  {
    "_id" : 2, "item" : "pecans", "price" : 20, "ordered" : 1 },
  {
    "_id" : 3, "item" : "cookies", "price" : 10, "ordered" : 60 }
] )

// 查询 item = almonds的文档
db.orders.aggregate([{
   
    $match: {
   
        item:"almonds"
    }
}])
// 查询orice >=10 的数据
db.orders.aggregate([{
   
    $match: {
   
        price:{
   $gte:10}
    }
}])

$group

聚合分组,类似于sql种的分组用法。

{
   
 $group:
   {
   
     _id: <expression>, // Group key
     <field1>: {
    <accumulator1> : <expression1> }, // 返回的值,通常是聚合函数
     ...
   }
 }

$limit

限制输出文档的个数。

// 获取books表中第一条数据
db.getCollection("books").aggregate([{
   
    $limit: 1
}])

$skip

跳过指定的个数的文档。

// 语法
{
    $skip: <positive 64-bit integer> }

1、跳过第一条数据

// 插入10条数据
db.stastistic.insertMany([
    {
    "_id": "2019Q1", "sales": 1950, "purchased": 1200 },
    {
    "_id": "2019Q2", "sales": 500, "purchased": 1700 }{
    "_id": "2019Q3", "sales": 1950, "purchased": 1200 },
    {
    "_id": "2019Q4", "sales": 500, "purchased": 1700 },
    {
    "_id": "2019Q5", "sales": 1950, "purchased": 1200 },
    {
    "_id": "2019Q6", "sales": 500, "purchased": 1700 },
    {
    "_id": "2019Q7", "sales": 1950, "purchased": 1200 },
    {
    "_id": "2019Q8", "sales": 500, "purchased": 1700 },
    {
    "_id": "2019Q9", "sales": 1950, "purchased": 1200 },
    {
    "_id": "2019Q10", "sales": 500, "purchased": 1700 },
])

// 跳过第一条数据
db.stastistic.aggregate([
    {
   
        $skip: 1
    }
])

2、配合上述$limit可以完成分页查询的效果

如按照每页5条,查询第二页的数据。

pageNumber:第几页,pageSize:数量,则

$skip 的 变量是 (pageNumber - 1) * pageSize

// 每页5条,查询第二页的树。
// (2 - 1) * 5 = 5
db.stastistic.aggregate([
    {
   
        $skip: 5
    },
    {
   
        $limit: 5
    }
])

$sort

排序。

// 说明:1:正序排列;-1:倒叙排列。也可以指定计算规则进行排序。
{
    $sort: {
    <field1>: <sort order>, <field2>: <sort order> ... } }

1、按照id正序排列

db.stastistic.aggregate([
    {
   
        $sort: {
   _id:1}
    }
])

$count

统计文档的数量。

// 查询score>80分的数据的个数为passing_scores
db.scores.aggregate(
    [{
   
        $match: {
   
            score: {
   
                $gt: 80
            }
        }
    },
    {
   
        $count: "passing_scores"
    }]
)

$unionWith

类似于sql中的union all的用法,将结果集进行合并。

// 定义
{
    $unionWith: {
    coll: "<collection>", pipeline: [ <stage1>, ... ] } }{
    $unionWith: "<collection>" }  // Include all documents from the specified collection

1、合并数据

// 插入数据
db.suppliers.insertMany([
  {
    _id: 1, supplier: "Aardvark and Sons", state: "Texas" },
  {
    _id: 2, supplier: "Bears Run Amok.", state: "Colorado"},
  {
    _id: 3, supplier: "Squid Mark Inc. ", state: "Rhode Island" },
])

db.warehouses.insertMany([
  {
    _id: 1, warehouse: "A", region: "West", state: "California" },
  {
    _id: 2, warehouse: "B", region: "Central", state: "Colorado"},
  {
    _id: 3, warehouse: "C", region: "East", state: "Florida" },
])

// 获取两个表中state
db.suppliers.aggregate([
    {
   
        $project: {
    state: 1, _id: 0 }
    },
    {
   
        $unionWith: {
   
            coll: "warehouses", pipeline: [{
   
                $project: {
    state: 1, _id: 0 }
            }]
        }
    }, {
   
        $group: {
    _id: "$state" }
    }
])
  • 第一阶段:只查询state属性
  • 第二阶段:合并warehousesstate属性
  • 第三阶段:利用分组过滤数据

2、统计多表中的数据进行分析

// 插入2017、2018、2019、2020销售数据清单
db.sales_2017.insertMany( [
  {
    store: "General Store", item: "Chocolates", quantity: 150 },
  {
    store: "ShopMart", item: "Chocolates", quantity: 50 },
  {
    store: "General Store", item: "Cookies", quantity: 100 },
  {
    store: "ShopMart", item: "Cookies", quantity: 120 },
  {
    store: "General Store", item: "Pie", quantity: 10 },
  {
    store: "ShopMart", item: "Pie", quantity: 5 }
] )

db.sales_2018.insertMany( [
  {
    store: "General Store", item: "Cheese", quantity: 30 },
  {
    store: "ShopMart", item: "Cheese", quantity: 50 },
  {
    store: "General Store", item: "Chocolates", quantity: 125 },
  {
    store: "ShopMart", item: "Chocolates", quantity: 150 },
  {
    store: "General Store", item: "Cookies", quantity: 200 },
  {
    store: "ShopMart", item: "Cookies", quantity: 100 },
  {
    store: "ShopMart", item: "Nuts", quantity: 100 },
  {
    store: "General Store", item: "Pie", quantity: 30 },
  {
    store: "ShopMart", item: "Pie", quantity: 25 }
] )

db.sales_2019.insertMany( [
  {
    store: "General Store", item: "Cheese", quantity: 50 },
  {
    store: "ShopMart", item: "Cheese", quantity: 20 },
  {
    store: "General Store", item: "Chocolates", quantity: 125 },
  {
    store: "ShopMart", item: "Chocolates", quantity: 150 },
  {
    store: "General Store", item: "Cookies", quantity: 200 },
  {
    store: "ShopMart", item: "Cookies", quantity: 100 },
  {
    store: "General Store", item: "Nuts", quantity: 80 },
  {
    store: "ShopMart", item: "Nuts", quantity: 30 },
  {
    store: "General Store", item: "Pie", quantity: 50 },
  {
    store: "ShopMart", item: "Pie", quantity: 75 }
] )

db.sales_2020.insertMany( [
  {
    store: "General Store", item: "Cheese", quantity: 100, },
  {
    store: "ShopMart", item: "Cheese", quantity: 100},
  {
    store: "General Store", item: "Chocolates", quantity: 200 },
  {
    store: "ShopMart", item: "Chocolates", quantity: 300 },
  {
    store: "General Store", item: "Cookies", quantity: 500 },
  {
    store: "ShopMart", item: "Cookies", quantity: 400 },
  {
    store: "General Store", item: "Nuts", quantity: 100 },
  {
    store: "ShopMart", item: "Nuts", quantity: 200 },
  {
    store: "General Store", item: "Pie", quantity: 100 },
  {
    store: "ShopMart", item: "Pie", quantity: 100 }
] )

// 统计四年各个产品的销售数量
db.sales_2017.aggregate([
    {
   $unionWith: "sales_2018"},
    {
   $unionWith: "sales_2019"},
    {
   $unionWith: "sales_2020"},
    {
   
        $group: {
   
            _id: "$item",
            total: {
   
                $sum: "$quantity"
            }
        }
    }
])

// 执行结果
{
    "_id" : "Chocolates", "total" : 1250 }
{
    "_id" : "Cookies", "total" : 1720 }
{
    "_id" : "Pie", "total" : 395 }
{
    "_id" : "Cheese", "total" : 350 }
{
    "_id" : "Nuts", "total" : 510 }

$unset

删除字段,在管道中等同于$project状态为0的操作。

// 删除单个属性
{
    $unset: "<field>" }
// 删除多个属性
{
    $unset: [ "<field1>", "<field2>", ... ] }

插入数据:

db.books.insertMany([
   {
    "_id" : 1, title: "Antelope Antics", isbn: "0001122223334", author: {
    last:"An", first: "Auntie" }, copies: [ {
    warehouse: "A", qty: 5 }, {
    warehouse: "B", qty: 15 } ] },
   {
    "_id" : 2, title: "Bees Babble", isbn: "999999999333", author: {
    last:"Bumble", first: "Bee" }, copies: [ {
    warehouse: "A", qty: 2 }, {
    warehouse: "B", qty: 5 } ] }
])

1、删除单个及多个字段

// 删除title字段
db.books.aggregate([{
   
    $unset: "title"
}])
// 删除title和isbn字段
db.books.aggregate([{
   
    $unset: ["title", "isbn"]
}])
</
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值