I have a collection with feeds. The documents are structured something like this:
{
  _id: '123',
  title: 'my title',
  openedBy: ['321', '432', '543'] // ID of users
}
Then I have users:
{
  _id '321',
  friends: ['432'] // ID of users
}
What I would like to accomplish is to get the number of friends that has opened the feeds fetched by the user. I do this now with a mapReduce, passing the friends of the user fetching the feeds. I do not think I am doing it correctly as I reduce by only returning the emit itself and I have to convert the result back to a normal query result on the finalizer:
    db.collection(collectionName).mapReduce(function () {
        var openedByFriendsLength = 0;
        for (var x = 0; x < friends.length; x++) {
            if (this.openedBy.indexOf(friends[x]) >= 0) {
                openedByFriendsLength++;
            }
        }
        emit(this._id, {
            title: this.title,
            openedByLength: this.openedBy.length,
            openedByFriendsLength: openedByFriendsLength
        });
    }, function (key, emits) {
        return emits[0];
    }, {
        out: 'getFeeds',
        scope: {
            friends: user.friends
        },
    }, function (err, collection) {
        collection.find().toArray(function (err, feeds) {
            // Convert the _id / value to a normal find result
            var resultFeeds = [];
            for (var x = 0; x < feeds.length; x++) {
                resultFeeds.push(feeds[x].value);
                resultFeeds[resultFeeds.length - 1]._id = feeds[x]._id;
            }
            callback(err, resultFeeds);
        });
    });
I have looked at aggregation, but I can not quite figure out how to do the same thing. Or is the structure of the documents here all wrong?
Thanks for any reply!