2013-10-05 35 views
0

我想了解如何在mongoDB中建立基本关系。我在文档中阅读了一下它,但它有点简洁。如何通过ID从相关文档中检索数据?

这应该很简单:我正在尝试记录展示次数列表和负责展示次数的用户。下面是日志文件的一些例子:

{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'} 

这里的用户文档的例子:

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

有没有一种方法来计算的,其“属于”文件的userId总数xxx-12345,其中type1

在上面的情况下,我想看到类似{ '1':3, '2':1 }的结果。

此外,是上述创建关系的可接受的方式?

+0

你想算每个用户的每个类型的展示次数?或者您想为特定用户ID计算每种类型的展示次数? – attish

回答

1

对于你的第一个问题Is there a way to count the total number of documents which "belong" to a userId of xxx-12345, where type is 1?,下面是解决方案:

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

为了得到(In the above case, I'd want to see a result like { '1':3, '2':1 }.)指定格式的解决方案,可以使用下面的代码:

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

这是什么错。 – Rajesh

0

您可以使用在2.2版本中引入的Aggregation Pipeline

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

这将输出:

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

其中 “_id” 是类型和“总”是计数型出现在用户“xxx-12345”

但是,如果你想获得只属于文档总数为“XXX-12345”里的类型是“1”你可以做这样的:

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

这将输出以下内容:

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

其中“count”是您正在查找的内容。

相关问题