0

I have collection Users:

{ "_id" : ObjectId("59fdc96ce166111e8da178f3"), "id" : 724207, "gamename" : "Meller", "reports" : [ { "action" : "Umbrella", "exp" : 64, "date" : 1509811977 }, { "action" : "Umbrella", "exp" : 53, "date" : 1509812077 }, { "action" : "Umbrella", "exp" : 55, "date" : 1509815977 } ], "squad" : [ { "squad" : "Temp", "date" : 1509880801 } ] }

I have this query:

db.getCollection('Users').aggregate([
    {
        $project:
            {
            _id : true,
            gamename: true,
            reports: true
            }
    },
    {
        $unwind : '$reports',
    },
    {
        $match : {
            'reports.date' : {'$gte': 1509815900, '$lte':1509816000}
        }
    },
    {
        $group : {
            _id : '$_id',
            //id: 'id',
            reports : {$addToSet : '$reports'}
        }
    }
])

It gives me what i want ( user reports for given period of time), however no gamename is in resulting set. How can i add it?

Thanks.

  • [`$first`](https://docs.mongodb.com/manual/reference/operator/aggregation/first/). You only get out what you put in, so you need an accumulator of some sort and `$first` fits the bill for after `$unwind`. You might also look at [`$filter`](https://docs.mongodb.com/manual/reference/operator/aggregation/filter/) instead of using `$unwind` in the first place. – Neil Lunn Nov 08 '17 at 21:11

1 Answers1

0

You can make a gamename a part of your grouping key and then you can use $project again to get the original structure back

db.getCollection('Users').aggregate([
    {
        $project:
            {
            _id : true,
            gamename: true,
            reports: true
            }
    },
    {
        $unwind : '$reports',
    },
    {
        $match : {
            'reports.date' : {'$gte': 1509815900, '$lte':1509816000}
        }
    },
    {
        $group : {
            _id : { _id: '$_id', gamename: '$gamename'},
            reports : {$addToSet : '$reports'}
        }
    },
    {
        $project : {
            reports: 1,
            _id : "$_id._id",
            gamename: "$_id.gamename"
        }
    }
])
mickl
  • 48,568
  • 9
  • 60
  • 89