【问题标题】:Count number of fields in a document mongo Java计算文档 mongo Java 中的字段数
【发布时间】:2016-03-15 11:15:18
【问题描述】:

我有一个包含以下文档的集合 -

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

我正在使用 mongo java 驱动程序 3.2.1。 该文档包含一个嵌入式文档“days”,其中包含每月每一天的特定计数。 我需要找到计数存在的天数。例如 - 对于上述文档,计数存在的天数是 3(每月的第 13、11 和 10 天)。 我知道如何在 mongo 控制台上获得计数 -

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

我需要把它转换成java代码。

【问题讨论】:

    标签: java mongodb


    【解决方案1】:

    也许您可以按如下方式重塑您的架构:

    { 
        "_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 变成一个对象数组,通过这种方式,您可以轻松地使用聚合管道了解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

    【讨论】:

    • $exists 不会使用索引,所以如果我们有数百万的记录,我认为它会更慢。请建议。
    猜你喜欢
    • 2018-06-16
    • 2017-09-30
    • 2011-09-26
    • 1970-01-01
    • 2012-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-29
    相关资源
    最近更新 更多