0

I am trying to use $push to push a field in an array during aggregation. The push is based on a condition. Here is my code.

Applications.aggregate(
        { $match: { playerUser: userId, playerFeedback: { $exists: false } } },
        { $group: {
            _id: '$format',
            players: { $push: { $cond: [{ $ne: ['$status', 'invite']}, "$player", null] }},
            invite: { $sum: { $cond: [{ $eq: ['$status', 'invite']}, 1, 0] } }
        } },
        {
            $lookup: {from: 'players', localField: 'players', foreignField: '_id', as: 'players'}
        },
        {
            $project : {
                "players.name" : 1,
                "players.Url" : 1,
                "invite" : 1,
                "applied": 1
            }
        }

This seems to work on my staging environment, which has mongodb v3.4. But it doesn't work on my production env, mongodb v3.2; although I am not sure if version is an issue here. Can someone help?

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Ankur Lathwal
  • 725
  • 1
  • 7
  • 24
  • MongoDB 3.2 does not support using an array for the `localField` with `$lookup`. For that version you are required to `$unwind` the array first. That keeps things compatible but it's not optimal. MongoDB 3.2 is actually past "end of life" for official support. Your production environment really should be using a supported version, but simply adding the `$unwind` fixes the process. – Neil Lunn May 04 '18 at 00:34
  • To clarify, the `$push` is not the problem, as you could have been aware of by simply running the first to aggregation stages. The result is not there because the `$lookup` cannot use the data in that form, and hence returns an "empty array" in the same `"players"` array you "pushed" items to in the earlier stage. – Neil Lunn May 04 '18 at 00:38

0 Answers0