mongotemplate聚合与独特的结果

时间:2014-11-25 12:34:34

标签: mongodb mongodb-query aggregation-framework spring-data-mongodb

我正在使用mongotemplate,我的收藏看起来像这样:

    {
    "_id": "theid",
    "tag": "taga",
    "somefield": "some value",
    "fieldC": {
        "anotherfielad": "more data",
        "an_array": [
            {
                "a": "abc",
                "b": 5
            },
            {
                "a": "bca",
                "b": 44
            },
            {
                "a": "ddd",
                "b": 21
            }
        ]
    }
}

{
    "_id": "anotherid",
    "tag": "taga",
    "somefield": "some other value",
    "fieldC": {
        "anotherfielad": "other more data",
        "an_array": [
            {
                "a": "ccc",
                "b": 6
            },
            {
                "a": "abc",
                "b": 99
            },
            {
                "a": "ddd",
                "b": 21
            }
        ]
    }
}

我需要从$ fieldC.an_array.a获得一个独特的结果 在这种情况下:(" abc"," bca"," ddd"," ccc")

此查询有效:

[
    {
        "$match": {
            "tag": "taga"
        }
    },
    {
        "$unwind": "fieldC.an_array"
    },
    {
        "$group": {
            "_id": null,
            "array": {
                "$addToSet": "fieldC.an_array.a"
            }
        }
    }
]

但我如何使用mongotemplate进行此操作?

2 个答案:

答案 0 :(得分:0)

我不认为这是更好的方式,但你可以通过以下方式实现这一目标:

DBObject unwind = new BasicDBObject(
    "$unwind", "fieldC.an_array"
);
DBObject match = new BasicDBObject(
    "$match", new BasicDBObject(
        "tag", "taga"
    )
);
DBObject group = new BasicDBObject("$group", JSON.parse(
    "{
        '_id': null,
        'array': {
            '$addToSet': 'fieldC.an_array.a'
        }
     }"
));
AggregationOutput output = mongoTemplate.getCollection("collectionName").aggregate(unwind, match, group);

if (output.results().iterator().hasNext()) {
    DBObject obj = (DBObject) output.results().iterator().next().get("array");
}

答案 1 :(得分:0)

这是您想要的AggregrationTests