mongodb的使用


Aggregation查询操作

筛选

{
    $match: {
        field1: "abc",
        field2: { $gt: 3}
    }
}
# 表示匹配出 1.字段field1的值为"abc" 且 2.字段field2的值大于3 的文档

条件操作符

  • $gt/$lt 大于/小于
  • $gte/$lte 大等于/小等于
  • $eq/$ne 等于/不等于
  • $regex 正则匹配

联表

/**
 * from: The target collection.
 * localField: The local join field.
 * foreignField: The target join field.
 * as: The name for the results.
 * pipeline: Optional pipeline to run on the foreign collection.
 * let: Optional variables to use in the pipeline field stages.
 */
{
  from: "schedule",
  localField: "name",
  foreignField: "schedule_name",
  as: "schedule_info"
}
# 表示 以当前集合的所有文档,关联另一个集合
# from表示关联的集合名称
# localField/foreignField分别表示关联的两个集合所用的字段
# as表示关联上的文档要存在的数组的名称

展开

/**
 * path: Path to the array field.
 * includeArrayIndex: Optional name for index.
 * preserveNullAndEmptyArrays: Optional
 *   toggle to unwind null and empty values.
 */
{
  path: "$schedule_info"
}
# 表示把一个数组字段展开,

聚合管道 aggregation pipeline

通过聚合管道的方式串联起多个stage进行查询

stage

$match

{$match: <query> }
{$match: {$expr: { <aggregation expression> } } }

筛选出与query内容相匹配的文档

$group

{
  $group:
    {
      _id: <expression>, // Group key, 
      <field1>: { <accumulator1> : <expression1> },
      ...
    }
 }

按照指定的_id的取值分组,_id可以使用字典来实现多个条件交叉下分组

$project

{ $project: { <specification(s)> } }

用来控制输出的文档要包含哪些字段

$lookup

{
   $lookup:
      {
         from: <foreign collection>,
         localField: <field from local collection's documents>,
         foreignField: <field from foreign collection's documents>,
         let: { <var_1>: <expression>, …, <var_n>: <expression> },
         pipeline: [ <pipeline to run> ],
         as: <output array field>
      }
}

用来关联另一个集合实现"left outer join"的功能
from指定用来关联的集合
localField/foreignField分别指出关联的字段
let用来定义变量
pipeline可以在关联操作之前在被关联的集合上指定一些stage
as用来指定关联到的结果存放的字段名

$unwind

{
  $unwind:
    {
      path: <field path>,
      includeArrayIndex: <string>,
      preserveNullAndEmptyArrays: <boolean>
    }
}

将文档按照其中某个数组字段的每个元素,拆分成多个元素
path指定该数组字段
includeArrayIndex指定一个字段用来保存元素在原数组中的下标
preserveNullAndEmptyArrays表示是否保留空数组

accumulator

link

  • addToSet: 对同一个group内取无序无重复集合
  • push: 对同一个group内取顺序数组队列

优化

建立索引

mongodb支持在数组字段上建立索引

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值