简体   繁体   English

java mongodb - 获取数组长度而不下载所有数据

[英]java mongodb - get array length without downloading all data

I'm using mongodb to store data for my java program and I have a collection with an array field that has a lot of things in it but i want only to get the length, without all the other data. 我正在使用mongodb存储我的java程序的数据,我有一个数组字段的集合,其中有很多东西,但我只想得到长度,没有所有其他数据。

Now i'm using this to get it: 现在我用它来得到它:

((UUID[])document.get("customers")).length

How can I make this not to download all the array? 我如何才能下载所有阵列?

A possible answer is to create an int that counts the pushes and the pulls of the array but it's not the cleanest method. 一个可能的答案是创建一个int来计算数组的推送和拉动,但它不是最干净的方法。

You are looking for aggregation framework where you can use the $size operator in your pipeline, this counts and returns the total the number of items in an array: 您正在寻找聚合框架 ,您可以在管道中使用$size运算符,这将计算并返回数组中项目的总数:

db.collection.aggregate([
    {
        "$project": {
            "_id": 0, "customer_count": { "$size": "$customers" }
         }
    }
]);

where the Java equivalent: Java等价物的位置:

DBObject projectFields = new BasicDBObject("_id", 0);
projectFields.put("customer_count", new BasicDBObject( "$size", "$customers" ));
DBObject project = new BasicDBObject("$project", projectFields);

AggregationOutput output = db.getCollection("collectionName").aggregate(project);

System.out.println("\n" + output);

You can use MongoDB's Aggregation Framework to get the size of the array. 您可以使用MongoDB的聚合框架来获取数组的大小。 For example, given the following document structure: 例如,给定以下文档结构:

> db.macross.findOne()
{
    "_id" : "SDF1",
    "crew" : [
            "Rick",
            "Minmay",
            "Roy",
            "Max",
            "Misa",
            "Milia"
    ]
}

get the size of the array 得到数组的大小

> db.macross.aggregate( 
    { $match: { _id: "SDF1" } }, 
    { $unwind: "$crew" }, 
    { $group: { _id: "", count: { $sum: 1 } } }, 
    { $project: { _id: 0, count: 1 } }
)
{ "count" : 6 }

More detailed and interesting examples are available in the docs . 文档中提供了更详细和有趣的示例。

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

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