1

我使用mongotemplate 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?

回答

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