nodejs+mongodb aggregate級聯(lián)查詢操作示例
本文實例講述了nodejs+mongodb aggregate級聯(lián)查詢操作。分享給大家供大家參考,具體如下:
最近完成了一個nodejs+mongoose的項目,碰到了mongodb的級聯(lián)查詢操作。情形是實現(xiàn)一個排行榜,查看某個公司(organization)下屬客戶中發(fā)表有效文ruan章wen最多的前十人。
Account表:公司的信息單獨存在一個account表里。
var AccountSchema = new Schema({ loginname: {type: String}, password: {type: String}, /** * 聯(lián)系方式 */ //賬戶公司名 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整理軟文并排序→級聯(lián)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); })); }) }); };
返回的結(jié)果格式(這里僅有兩條記錄,實際為前十):
[ { _id: { customerId: 559a5b6f51a446602032fs21 }, number: 5, customerName: 'test2', mobile:22 } , { _id: { customerId: 559a5b6f51a446602041ee6f }, number: 1, customerName: 'test1', mobile: 11 } ]
希望本文所述對大家nodejs程序設(shè)計有所幫助。
相關(guān)文章
nodejs簡單訪問及操作mysql數(shù)據(jù)庫的方法示例
這篇文章主要介紹了nodejs簡單訪問及操作mysql數(shù)據(jù)庫的方法,結(jié)合實例形式分析了nodejs創(chuàng)建mysql連接、執(zhí)行sql語句及關(guān)閉連接等相關(guān)操作技巧,需要的朋友可以參考下2018-03-03