mongodb 中非常好用的 Aggregate


mongodb 中非常好用的 Aggregate

aggregate 翻譯過來是聚合的意思, 但是在實際的使用的它的體驗特別像linux中的管道, 每個管道處理完之后再把結果交個下一個管道, 你的數據就像水流, 最后通過各個管道你能夠得到你想要的數據

我們一般用Aggregate做什么

aggregate查詢文檔

  1. 聚合 平均數 等數據處理 $group $sum
  2. 地理位置信息 $geoNear
  3. 基本上mongodb的所有查詢操作我們都可以用 aggregate實現, 用好這個基本上是萬金油了

在這里我主要想記錄一下mongodb在地理位置信息查詢中使用到的技術,不僅可以查詢到 距離 還可以按照距離排序

$geoNear 地理位置信息查詢

首先我們的坐標數據在庫里面怎么存, 類型為 Array , 記得加 2d 索引, 當然還有3d 索引, 目前還沒有用到

   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 你的過濾條件                                                               

有一個很有意思的地方是 $geoNear 前面不可以使用 $match 所以在這里有一個 query屬性來補齊這種遺憾

但是你可以在 后面 使用$match 對查到的所有地理位置信息數據做再一次的篩選

$lookup mongodb中的聯表查詢

$lookup 是在比較新的mongodb版本中才能使用的屬性, 當然這個屬性也是用於 aggregate中的, 它補齊了之前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 }
                }
            ]);

memberinfo 與 user 表在這里我想要獲取 memberinfo localField: 'user' 為外鍵對應 user表 foreignField: '_id' _id字段他的額外屬性...

說白了 我的會員表里面只存了用戶的id 現在我想要拿到用戶的 其它信息...

附上鏈接吧 $lookup

寫在最后

當然說他是查詢萬金油他當然支持 定義數據的輸出 $skip 跳過多少記錄 $limit $sort 等常規操作


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM