2

I have two collections in mongodb.

requests collection

  1. _id
  2. ipaddress
  3. createdon

geoip collection

  1. _id
  2. ipaddress
  3. country
  4. city

geoip is a look up table for IP address, which is unique here.

I need the following result, to find the total number of requests from each country. In other words, the following 2 columns.

country and recordcount (from requests collection based on the ipaddress)

Since this requires grouping 2 separate collections and combining them to get the results, I am at a loss here.

1 Answer 1

4

You would need to use a $lookup stage operation which is used to perform joins with other collections and fetch the results. Then group on the selected field to the required counts.

[
 {$lookup: {
    from: 'geoip',
    localField: 'ipaddress',
    foreignField: 'ipaddress',
    as: 'data'
 }},
 {$unwind: 'data'},
 {$group: {_id: '$data.country', count: {$sum: 1}}}

]
Sign up to request clarification or add additional context in comments.

4 Comments

This works great! Is it possible to achieve this through map reduce as lookup is not supported in older mongodb versions.
@FoxShrill I havn't used map-reduce a lot. You can probably read up on this here tebros.com/2011/07/…
map/reduce did not support any form of cross-collection join; the best you could do would be to run two separate map/reduce steps and have the second one "reduce" the output of the first, filling in the missing data... but it would be really inefficient
but how to do it if we need to join 3 collections for ex?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.