2016-03-15 208 views
0

我有一个包含下列文件的集合 -计数蒙戈的Java

{ 
    "_id" : ObjectId("56e7a51b4a66e30330151847"), 
    "host" : "myTestHost.com", 
    "sessionId" : "daxxxxxx-xxxx-xxxx-xxxx-xxxxxxx1", 
    "ssoId" : "[email protected]", 
    "days" : { 
      "13" : NumberLong(130), 
      "11" : NumberLong(457), 
      "10" : NumberLong(77) 
    }, 
    "count" : NumberLong(664), 
    "timeStamp" : NumberLong("1458021713370") 
} 

我使用蒙戈Java驱动程序3.2.1。 本文档包含嵌入式文档“天”,该文档包含每月每天的特定计数。 我需要查找计数所在的天数。例如 - 对于上面提到的文件,计数存在的天数为3(每月的第13,第11和第10天)。 我知道如何让蒙戈控制台上的计数 -

mongos>var count = 0; 
mongos> db.monthData.find({},{days:1}).forEach(function(record){for(f in record.days) { count++;}}); 
mongos> count; 

我需要将其转换为Java代码。

回答

1

也许你可以重塑你的架构如下:

{ 
    "_id" : ObjectId("56e7a51b4a66e30330151847"), 
    "host" : "myTestHost.com", 
    "sessionId" : "daxxxxxx-xxxx-xxxx-xxxx-xxxxxxx1", 
    "ssoId" : "[email protected]", 
    "days" : [ 
     { 
      "13" : NumberLong(130) 
     }, 
     { 
      "11" : NumberLong(457) 
     }, 
     { 
      "10" : NumberLong(77) 
     } 
    ], 
    "count" : NumberLong(664), 
    "timeStamp" : NumberLong(1458021713370) 
} 

days成为对象的数组,并以这种方式,你可以很容易地使用聚合管道知道有多少元素在days阵列:

>db.collection.aggregate(
    [ 
     {$match:{days:{"$exists":1}}}, 
     {$project:{ 
      numberOfDays: {$size:"$days"}, 
      _id:1} 
     } 
    ] 
) 

聚集回报:

{ "_id" : ObjectId("56e7a51b4a66e30330151847"), "numberOfDays" : 3 } 

运用聚合管道与Java驱动程序见aggregateAggregateIterableBlock和阅读Data Aggregation with Java Driver

+0

$存在不会使用索引,所以如果我们在数以百万计的记录它会慢一些,我认为。请建议。 – viren