问题
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