mongotemplate aggregation with unique results

末鹿安然 提交于 2019-12-11 10:16:19

问题


I am using mongotemplate , my collection look like this:

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

I need to get a unique result from $fieldC.an_array.a in this case: ("abc","bca","ddd","ccc")

this query works:

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

but how do I do it using mongotemplate ?


回答1:


I don't think it is the better way, but you can achieve this with:

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");
}



回答2:


Here is what you want AggregrationTests.



来源:https://stackoverflow.com/questions/27126909/mongotemplate-aggregation-with-unique-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!