从数组MongoDB中获取唯一ObjectId的数量

时间:2018-02-05 14:43:37

标签: java mongodb mongodb-query aggregation-framework

我刚开始使用MongoDb并且不了解很多东西。 我需要写一个聚合请求。 这是JSON文档结构。

{ 
    "_id" : ObjectId("5a72f7a75ef7d430e8c462d2"), 
    "crawler_id" : ObjectId("5a71cbb746e0fb0007adc6c2"), 
    "skill" : "stack", 
    "created_date" : ISODate("2018-02-01T13:19:03.522+0000"), 
    "modified_date" : ISODate("2018-02-01T13:22:23.078+0000"), 
    "connects" : [
        {
            "subskill" : "we’re", 
            "weight" : NumberInt(1), 
            "parser_id" : [
                ObjectId("5a71d88d5ef7d41964fbec11")
            ]
        }, 
        {
            "subskill" : "b1", 
            "weight" : NumberInt(2), 
            "parser_id" : [
                ObjectId("5a71d88d5ef7d41964fbec11"), 
                ObjectId("5a71d88d5ef7d41964fbec1b")
            ]
        }, 
        {
            "subskill" : "making", 
            "weight" : NumberInt(2), 
            "parser_id" : [
                ObjectId("5a71d88d5ef7d41964fbec1b"), 
                ObjectId("5a71d88d5ef7d41964fbec1c")
            ]
        }, 
        {
            "subskill" : "delivery", 
            "weight" : NumberInt(2), 
            "parser_id" : [
                ObjectId("5a71d88d5ef7d41964fbec1c"), 
                ObjectId("5a71d88d5ef7d41964fbec1e")
            ]
        }
    ]
}

我需要结果返回技能名称和唯一parser_id的数量。 在这种情况下,结果应为:

[
   {
    "skill": "stack",
    "quantity": 4
    }
]

其中“堆叠” - 技能名称, 和“数量” - 唯一parser_id的计数。

ObjectId("5a71d88d5ef7d41964fbec11")
ObjectId("5a71d88d5ef7d41964fbec1b")
ObjectId("5a71d88d5ef7d41964fbec1c")
ObjectId("5a71d88d5ef7d41964fbec1e")

有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

鉴于你问题中提供的文件,这个命令......

db.collection.aggregate([
    { $unwind: "$connects" },

    // count all occurrences
    { "$group": { "_id": {skill: "$skill", parser_id: "$connects.parser_id"}, "count": { "$sum": 1 } }},

    // sum all occurrences and count distinct
    { "$group": { "_id": "$_id.skill", "quantity": { "$sum": 1 } }},

    // (optional) rename the '_id' attribute to 'skill'
    { $project: { 'skill': '$_id', 'quantity': 1, _id: 0 } }
])

...将返回:

{
    "quantity" : 4,
    "skill" : "stack"
}

上述命令按skillconnects.parser_id分组,然后获得这些组的明确计数。

您的命令包含java标记,因此我怀疑您希望使用MongoDB Java驱动程序执行相同的命令。下面的代码(使用MongoDB Java驱动程序v3.x)将返回相同的结果:

MongoClient mongoClient = ...;

MongoCollection<Document> collection = mongoClient.getDatabase("...").getCollection("...");

List<Document> documents = collection.aggregate(Arrays.asList(
        Aggregates.unwind("$connects"),
        new Document("$group", new Document("_id", new Document("skill", "$skill").append("parser_id", "$connects.parser_id"))
                .append("count", new Document("$sum", 1))),
        new Document("$group", new Document("_id", "$_id.skill").append("quantity", new Document("$sum", 1))),
        new Document("$project", new Document("skill", "$_id").append("quantity", 1).append("_id", 0))
)).into(new ArrayList<>());

for (Document document : documents) {
    logger.info("{}", document.toJson());
}

注意:此代码故意使用new Document(<pipeline aggregator>, ...)形式而不是Aggregators实用程序,以便更容易查看 shell命令与其Java等效项之间的转换。< / p>

答案 1 :(得分:0)

使用$project

尝试$reduce

$setUnion用于仅保留不同的ID,最后$size用于获取不同的数组计数

db.col.aggregate(
    [
        {$project : {
                _id : 0,
                skill : 1,
                quantity : {$size :{$reduce : {input : "$connects.parser_id", initialValue : [] , in : {$setUnion : ["$$value", "$$this"]}}}}
            }
        }
    ]
).pretty()

结果

{ "skill" : "stack", "quantity" : 4 }