이 글은 주로 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);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 table
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 → Cascade 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);
}));
})
});
};반환된 결과 형식(여기에는 레코드가 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!