简体   繁体   English

计算文档mongo Java中的字段数

[英]Count number of fields in a document mongo Java

I have a collection containing following documents - 我有一个包含以下文件的收藏集-

{
    "_id" : ObjectId("56e7a51b4a66e30330151847"),
    "host" : "myTestHost.com",
    "sessionId" : "daxxxxxx-xxxx-xxxx-xxxx-xxxxxxx1",
    "ssoId" : "xxxxxx@gmail.com",
    "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. 我正在使用mongo java驱动程序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). 我需要找到存在计数的天数。例如-对于上面提到的文档,存在计数的天数是3(每月的第13、11和10天)。 I know how to get the count on mongo console - 我知道如何在mongo控制台上计数-

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. 我需要将其转换为Java代码。

Maybe you can reshape your schema as follow: 也许您可以按照以下方式重塑架构:

{ 
    "_id" : ObjectId("56e7a51b4a66e30330151847"), 
    "host" : "myTestHost.com", 
    "sessionId" : "daxxxxxx-xxxx-xxxx-xxxx-xxxxxxx1", 
    "ssoId" : "xxxxxx@gmail.com", 
    "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: days成为对象数组,通过这种方式,您可以轻松地使用聚合管道来了解days数组中有多少个元素:

>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 要将Aggregation Pipeline与Java驱动程序一起使用,请参见aggregateAggregateIterableData Aggregation with Java Driver Block和读取Data Aggregation with Java Driver

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM