On this forum I am probably one of the most avidly not in favor in mongo, but recently, I discovered mongo 3.2 and the aggregation framework
I have found that this has completely worked out almost every frustration I have with mongoDB and it simply works great. With $lookup
, $group
, $unwind
, and $match
it’s really amazing what you can do.
This is probably the best example. Say you have Players
. Players
can belong to many games, and have many roles
in that game. The document can be structured like this:
{
_id: '1234',
games: [{
slug: "game-1",
// ... more stuff here
}],
roles: [{
'game-1': 'player'
}]
}
It’s much quicker to get a big document containing all the data you need
db.players.aggregate([{
// separate document for every game
$unwind: '$games',
// make object for each game and add a list of players
$group: {
_id: '$games.slug',
players: {
$addToSet: '$_id'
}
},
// perform lookup on all player profiles
$lookup: {
from: 'games',
localField: '_id',
foreignField: 'slug',
as: 'game'
}
}]);
And the result could come out looking like this:
[{
game: {
name: 'Game 1',
slug: 'game-1'
},
players: ['1', '2', '3']
}, {
game: {
name: 'Game 2',
slug: 'game-2'
},
players: ['4']
}]
Is there any plans for these two changes to be added? I find they’re incredibly powerful