首页 > 解决方案 > Mongoose:$lookup 后的 $project 不显示字段

问题描述

我有两个模型user.jsschedule.js并且我有一个查询(聚合),我需要使用$lookup来“加入”这些模型。在 $lookup 之后,我使用了一个$project来选择我想在查询结果中显示的字段,但这些字段scheduleStartscheduleEnd没有显示在我的结果中。

User.js(模型)

  name: {
        type: String,
        required: true
    },
    firstName: {
        String
    },
    lastName: {
        String
    },
    storeKey: {
        type: String,
        required: true
    },
    avatar: String,
    birthday: String,
    phone: {
        type: String
    },
    doc: String,
    email: {
        type: String
    },...

Schedule.js(模型)

 service: {
    id: {
      type: String
    },
    name: {
      type: String,
      required: true
    },
    filters: [String]
  },
  info: {
    channel: {
      type: String,
      required: true,
      default: 'app'
    },
    id: String,
    name: String
  },
  scheduleDate: {
    type: String,
    required: true
  },
  scheduleStart: {
    type: String,
    required: true
  },
  scheduleEnd: {
    type: String,
    required: true
  },

我的查询

 User.aggregate([{
      $match: {
        storeKey: req.body.store,     
      }
    },
    {
      $group: {
        _id: {
          id: "$_id",
          name: "$name",
          cpf: "$cpf",      
          phone: "$phone",
          email: "$email",
          birthday: "$birthday",
          lastName: "$lastname"      
        },
        totalServices: {
          $sum: "$services"
        },    
      }
    },
    {
      $lookup: {
        from: "schedules",
        localField: "_id.phone",
        foreignField: "customer.phone",
        as: "user_detail"
      }  
    },  
    {
      $project: {
        _id: 1,
        name: 1,
        name: 1,
        cpf: 1,      
        phone: 1,
        email: 1,
        birthday: 1,
        totalServices: 1,
        totalValue: { "$sum": "$user_detail.value" },
        scheduleStart: 1,
        scheduleEnd: 1,
        count: {
          $sum: 1
        }
      }
    }   
  ])...

我的查询结果:

count: 1
totalServices: 89
totalValue: 2374
_id:{
birthday: "1964-03-18",
cpf: "319335828",
email: "jdoe@gmail.com.br",
id: "5b1b1dcce1ab2a8eb580f",
name: "Jonh Doe",
phone: "11996370565"
}

标签: javascriptmongodbmongooseaggregation-framework

解决方案


您可以将以下$project阶段与$arrayElemAt聚合一​​起使用

{ '$project': {
  '_id': 1,
  'name': 1,
  'cpf': 1,      
  'phone': 1,
  'email': 1,
  'birthday': 1,
  'totalServices': 1,
  'totalValue': { '$sum': '$user_detail.value' },
  'scheduleStart': { '$arrayElemAt': ['$user_detail.scheduleStart', 0] },
  'scheduleEnd': { '$arrayElemAt': ['$user_detail.scheduleEnd', 0] },
  'count': { '$sum': 1 }
}} 

推荐阅读