前言aggregate查询文档 基本上mongodb的所有查询操作我们都可以用 aggregate实现, 用好这个基本上是万金油了 $geoNear 地理位置信息查询 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); 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属性来补齐这种遗憾 $lookup mongodb中的联表查询 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 } } ]);为外键对应 user表 foreignField: '_id' $lookup limit $sort 等常规操作 总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对自学php网的支持。
查看更多关于mongodb中非常好用的Aggregate入门教程的详细内容...