各位用户为了找寻关于mongodb中非常好用的Aggregate入门教程的资料费劲了很多周折。这里教程网为您整理了关于mongodb中非常好用的Aggregate入门教程的相关资料,仅供查阅,以下为您介绍关于mongodb中非常好用的Aggregate入门教程的详细内容

前言

aggregate 翻译过来是聚合的意思, 但是在实际的使用的它的体验特别像linux中的管道, 每个管道处理完之后再把结果交个下一个管道, 你的数据就像水流, 最后通过各个管道你能够得到你想要的数据

我们一般用Aggregate做什么

aggregate查询文档

聚合 平均数 等数据处理 group sum 地理位置信息 $geoNear 基本上mongodb的所有查询操作我们都可以用 aggregate实现, 用好这个基本上是万金油了

在这里我主要想记录一下mongodb在地理位置信息查询中使用到的技术,不仅可以查询到 距离 还可以按照距离排序

$geoNear 地理位置信息查询

首先我们的坐标数据在库里面怎么存, 类型为 Array , 记得加 2d 索引, 当然还有3d 索引, 目前还没有用到

? 1 2 3 4 5 6 const storeschema = new mongoose.Schema({  name: { type: String, required: true },  point: { type: Array, required: true }, // [lon, lat] }); storeschema.index({ point: '2d' }); return mongoose.model('store', storechema);

然后按照就是地理查询代码了

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 this.ctx.model.Store.aggregate([{     $geoNear: {      spherical: true, // spherical 是否按照球形状来求距离      distanceMultiplier: 6378137,      maxDistance: 10000,      near: [ lon1, lat1 ],      distanceField: 'dist',      key: 'point',      query: {      }     },  },  //distanceMultiplier 这个参数是用于确定你返回的距离是什么单位 6378137 的单位是m  //maxDistance 查询的最大距离 // near 中心点坐标 // distanceField 距离放在哪个属性 // key 保存坐标数据的地方 // query 你的过滤条件

有一个很有意思的地方是 match 所以在这里有一个 query属性来补齐这种遗憾

但是你可以在   后面 使用$match 对查到的所有地理位置信息数据做再一次的筛选

$lookup mongodb中的联表查询

$lookup 是在比较新的mongodb版本中才能使用的属性, 当然这个属性也是用于 aggregate中的, 它补齐了之前mongodb中无法联表的遗憾

看代码

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 await this.ctx.model.MemberInfo.aggregate([         {           $match: { store: new ObjectId(store) }         },         {           $lookup: {             from: 'users',             localField: 'user',             foreignField: '_id',             as: 'user'           }         },         {           $replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: [ '$user', 0 ] }, '$$ROOT' ] } }         },         {           $match: { 'certification.name': { $regex: search } }         },         {           $project: { _id: 1 }         }       ]);

memberinfo 与 user 表在这里我想要获取 memberinfo  localField: 'user' 为外键对应 user表 foreignField: '_id' _id字段他的额外属性...

说白了 我的会员表里面只存了用户的id  现在我想要拿到用户的 其它信息...

附上链接吧 $lookup

写在最后

当然说他是查询万金油他当然支持 定义数据的输出  limit $sort 等常规操作

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。

原文链接:https://juejin.im/post/5c0dda435188255c823cc1c4