溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

nodejs+mongodb aggregate級聯查詢的示例分析

發布時間:2021-07-22 14:23:28 來源:億速云 閱讀:263 作者:小新 欄目:web開發

小編給大家分享一下nodejs+mongodb aggregate級聯查詢的示例分析,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

具體如下:

最近完成了一個nodejs+mongoose的項目,碰到了mongodb的級聯查詢操作。情形是實現一個排行榜,查看某個公司(organization)下屬客戶中發表有效文ruan章wen最多的前十人。

Account表:公司的信息單獨存在一個account表里。

var AccountSchema = new Schema({
  loginname: {type: String},
  password: {type: String},
  /**
   * 聯系方式
   */
  //賬戶公司名
  comName: {type: String},
  //地址
  address: {type: String},
  //公司介紹
  intro: {type: String}
});
mongoose.model('Account', AccountSchema);

Cusomer表:公司的客戶群。

var CustomerSchema = new Schema({
  /**
   * 基本信息
   */
  //密碼
  password: {type: String},
  //歸屬于哪個Account
  belongToAccount: {type: ObjectId, ref: 'Account'},
  //手機號,登錄用
  mobile: {type: String},
  //真實姓名
  realname: {type: String}
});
CustomerSchema.index({belongToAccount: 1, mobile: 1}, {unique: true});
mongoose.model('Customer', CustomerSchema);

article表

var articleSchema= new Schema({
  belongToAccount: {type: ObjectId, ref: 'Account'},
  title: {type: String},
  text: {type: String},
  createTime: {type: Date, default: Date.now},
  author: {type: ObjectId, ref: 'Customer'},
  //0,待確認,1 有效 ,-1 無效
  status: {type: Number, default: 0}
});
articleSchema.index({belongToAccount: 1, createTime:-1,author: 1}, {unique: false});
mongoose.model('article', articleSchema);

這里要做的就是,由accountId→aggregate整理軟文并排序→級聯author找到作者的姓名及其他信息。

代碼如下:

exports.getRankList = function (accountid, callback) {
  AticleModel.aggregate(
    {$match: {belongToAccount: mongoose.Types.ObjectId(accountid), status: 1}},
    {$group: {_id: {customerId: "$author"}, number: {$sum: 1}}},
    {$sort: {number: -1}}).limit(10).exec(function (err, aggregateResult) {
    if(err){
      callback(err);
      return;
    }
      var ep = new EventProxy();
      ep.after('got_customer', aggregateResult.length, function (customerList) {
        callback(null, customerList);
      });
       aggregateResult.forEach(function (item) {
        Customer.findOne({_id: item._id.customerId}, ep.done(function (customer) {
          item.customerName = customer.realname;
          item.customerMobile=cusomer.mobile;
          // do someting
          ep.emit('got_customer', item);
        }));
      })
    });
};

返回的結果格式(這里僅有兩條記錄,實際為前十):

[ { _id: { customerId: 559a5b6f51a446602032fs21 }, number: 5,
customerName: 'test2',
mobile:22 } ,
{ _id: { customerId: 559a5b6f51a446602041ee6f }, number: 1,
customerName: 'test1',
mobile: 11 } ]

以上是“nodejs+mongodb aggregate級聯查詢的示例分析”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女