猫鼬:$ lookup之后的$ project不显示字段

时间:2018-12-05 16:52:34

标签: javascript mongodb mongoose aggregation-framework

我有两个模型 user.js schedule.js ,并且我有一个查询(汇总),我需要使用$lookup来“加入”这些模型。在$ lookup之后,我使用$project来选择要在查询结果中显示的字段,但是字段python -m pip install --upgrade pipscheduleStart不在我的查询中结果。

User.js(模型)

scheduleEnd

Schedule.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
    },...

我的查询

 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
        }
      }
    }   
  ])...

1 个答案:

答案 0 :(得分:1)

您可以在$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 }
}}