简体   繁体   中英

Mongo map reduce or aggregate strategy

So I've gotten by with Mongo till now, without having to do anything that complex. But now I'm up against something.

I've got an Publisher model and a User model.

  • Users have an array of publisherIds.
  • so user.following = [1,2,3,4];

I'm building an admin table, and I need to show all publishers, and their number of followers.

Obviously I can't loop over each publisher and run a mongo query there, so what approach should I take?

Collection 1 Users

{
    id: 1,
    name: 'fred',
    following: [1,2,3,4],
},{
    id: 2,
    name: 'andy',
    following: [1,2]
},{
    id: 3,
    name: 'stephen',
    following: [1]
}

Desired output of collection 2 Publishers

{
    publisherId: 1,
    numberOfFollowers: 3
},{
    publisherId: 2,
    numberOfFollowers: 2
},{
    publisherId: 3,
    numberOfFollowers: 1
}

Map Reduce strategy can be a little slower and a lot faster than aggregation framework depending on size of data. MapReduce would run JavaScript in a separate thread and use the code you provide to emit and reduce parts of your document to aggregate on certain fields. You can certainly look at the exercise as aggregating over each "fieldValue". Aggregation framework can do this as well but would be much faster as the aggregation would run on the server in C++ rather than in a separate JavaScript thread. Also

The MongoDB aggregation pipeline consists of stages. Each stage transforms the documents as they pass through the pipeline. Pipeline stages do not need to produce one output document for every input document; eg, some stages may generate new documents or filter out documents. Pipeline stages can appear multiple times in the pipeline.

在此处输入图片说明

More reading: Is Mongodb Aggregation framework faster than map/reduce?

And to your example, here you go:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM