ホームページ >ウェブフロントエンド >jsチュートリアル >nodejs+mongodb集約カスケードクエリ操作の例
この記事では主にnodejs + mongodb集約カスケードクエリ操作を紹介し、nodejsに基づくmongodbデータベースカスケードクエリの関連操作スキルを例の形式で分析します。必要な友人はそれを参照できます
この記事の例は、 nodejs+mongodb 集約レベルの結合クエリ操作。参考のために皆さんと共有してください。詳細は次のとおりです:
私は最近、nodejs+mongoose プロジェクトを完了し、mongodb のカスケード クエリ操作に遭遇しました。ある企業(組織)の顧客の中で最も有効な記事を公開した人を上位10名まで表示するランキングリストを実装したいという状況です。
アカウント テーブル: 会社情報は別のアカウント テーブルに保存されます。
var AccountSchema = new Schema({
loginname: {type: String},
password: {type: String},
/**
* 联系方式
*/
//账户公司名
comName: {type: String},
//地址
address: {type: String},
//公司介绍
intro: {type: String}
});
mongoose.model('Account', AccountSchema);顧客テーブル: 会社の顧客ベース。
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);記事テーブル
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 → 集計 → カスケード著者順に整理して並べ替えて、著者名やその他の情報を見つけることです。
コードは次のとおりです:
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);
}));
})
});
};返される結果の形式 (ここには 2 つのレコードしかありません。実際には上位 10 件です):
[ { _id: { customerId: 559a5b6f51a446602032fs21 }, number: 5,
customerName: 'test2',
mobile:22 } ,
{ _id: { customerId: 559a5b6f51a446602041ee6f }, number: 1,
customerName: 'test1',
mobile: 11 } ]上記は、すべての人にとって役立つことを願っています。未来。
関連記事:
設定可能なログインフォームコードのVue.js実装の詳細説明
以上がnodejs+mongodb集約カスケードクエリ操作の例の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。