Question

I'm trying to understand how to set up basic relations in mongoDB. I've read a bit about it in the documentation but it's a little terse.

This should be pretty simple: I'm trying to log a list of impressions and the users who are responsible for the impressions. Here's some examples of log documents:

{type: '1', userId:'xxx-12345'}
{type: '1', userId:'xxx-12345'}
{type: '1', userId:'xxx-12345'}
{type: '2', userId:'zzz-84638'}
{type: '2', userId:'xxx-12345'}

Here's an example of a user document:

{userId: 'xxx-12345', location: 'US'}

Is there a way to count the total number of documents which "belong" to a userId of xxx-12345, where type is 1?

In the above case, I'd want to see a result like { '1':3, '2':1 }.

Also, is the above an acceptable way of creating the relationships?

Was it helpful?

Solution

For your 1st question Is there a way to count the total number of documents which "belong" to a userId of xxx-12345, where type is 1?, below is the solution:

db.impressions.aggregate({
                           $match: {
                                userId: 'xxx-12345',
                                type: 1
                           }
                         },
                         {
                              $group: { _id: null, count: { $sum: 1 } }
                         });

To get the solution in format you specified (In the above case, I'd want to see a result like { '1':3, '2':1 }.), use below code:

db.impressions.aggregate({
                       $match: {
                            userId: 'xxx-12345',
                       }
                     },
                     {
                          $group: { _id: '$type', totalImpressions: { $sum: 1 } }
                     });

OTHER TIPS

You can use the Aggregation Pipeline introduced in version 2.2:

db.a.aggregate([
  { $match: { userId: 'xxx-12345' } },
  { $group: { _id: "$type", total: { $sum: 1 } } }
])

This will output:

{
        "result" : [
                {
                        "_id" : "2",
                        "total" : 1
                },
                {
                        "_id" : "1",
                        "total" : 3
                }
        ],
        "ok" : 1
}

where "_id" is the type and "total" is the count that type appears in user "xxx-12345".

However, if you want to get only the total number of documents which belong to "xxx-12345" where the type is "1" you can do it like this:

db.a.aggregate([
  { $match: { userId: 'xxx-12345', type: "1" } },
  { $group: { _id: null, count: { $sum: 1} } }
])

which will output the following:

{ "result" : [ { "_id" : null, "count" : 3 } ], "ok" : 1 }

where "count" is what you're looking for.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top