问题描述:

I have a collection containing following documents -

{

"_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")

}

I am using mongo java driver 3.2.1.

This document contains an embedded document 'days', that holds a specific count for each day of month.

I need to find the number of days for which a count is present.For example - for above document mentioned, the number of days for which count is present is 3 (13th, 11th and 10th day of month).

I know how to get the count on mongo console -

mongos>var count = 0;

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

mongos> count;

I need to convert this to java code.

网友答案:

Maybe you can reshape your schema as follow:

{ 
    "_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 becomes an array of objects and in this way you can easily use aggregation pipeline to know how many elements are in days array:

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

The aggregation returns:

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

To use Aggregation Pipeline with Java driver see aggregate, AggregateIterable, Block and read Data Aggregation with Java Driver

相关阅读:
Top