>  기사  >  웹 프론트엔드  >  계단식 쿼리 구현 단계 집계

계단식 쿼리 구현 단계 집계

php中世界最好的语言
php中世界最好的语言원래의
2018-05-10 14:15:052037검색

이번에는 Aggregate Cascade 쿼리 구현 단계를 알려드리겠습니다. Aggregate Cascade 쿼리 구현을 위한 주의사항은 무엇인가요? 실제 사례를 살펴보겠습니다.

저는 최근 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);
        }));
      })
    });
};

반환된 결과 형식(여기에는 두 개의 레코드만 있으며 실제로 상위 10개):

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

이 기사의 사례를 읽은 후 방법을 마스터했다고 믿습니다. 정보, PHP 중국어 웹 사이트 기사에서 기타 관련 사항에 주목하십시오!

추천 자료:

JS를 사용하여 동적으로 생성된 요소에 이벤트를 추가하는 단계에 대한 자세한 설명

vue는 프런트 엔드 페이지에 표시하기 위해 이미지를 데이터베이스에 업로드합니다

위 내용은 계단식 쿼리 구현 단계 집계의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.