如何在吗啡中进行聚合?

How to perform aggregation in morphia?

我有一个对象的 List,我需要在 Morphia 中执行查询,以从给定的 String 的另一个嵌入 List 中获得唯一结果对象。

对象Class:

@Entity
public class Fruits {
  @NotNull private Long id;
  @NotNull private List<String> categories;
}

Json格式的数据:

水果:

 {[
  "id": 1234566,
  "categories": ["A", "B", "C", "D"]
 ],
 [
  "id": 32434,
  "categories": ["A", "C", "E", "F"]
 ],
 [
  "id": 32434,
  "categories": ["A", "L", "M", "N"]
 ] 
}

聚合结果应该是:

[A,C,B,D,E,F,L,M,N]

输出是排序的形式。我怎样才能在吗啡中实现这一点?我试图搜索官方文档,但找不到提示。

任何帮助或提示都将不胜感激。谢谢

编辑-1

List<Fruits> fruitList = fruitControllerDao.search(fruitList);

List<Category> categories = new ArrayList<>();
datastore.createAggregation(Fruits.class)
         .unwind("categories")
         .group(Group.id(Group.grouping("categories")))
         .sort(Sort.ascending("_id.categories"))
         .project(Projection.projection("_id").suppress(), 
          Projection.projection("categories", "_id.categories"))

         .aggregate(Category.class).forEachRemaining(categories::add);

并且我已经创建了

class Category {
   private String category;
}

fruitList 中的数据无法使用,我需要在 fruitList(检查 JSON 格式)本身上应用 aggregation

您可以使用以下代码通过聚合管道获取唯一类别并对类别进行排序。

准备查询过滤器:

Query<Fruits> query = datastore.createQuery(Fruits.class);
Iterator<Fruits> fruitIterator = fruitList .iterator();
CriteriaContainer orQuery = query.or();
while(fruitIterator.hasNext()) {
      Fruits fruit = fruitIterator.next();
      orQuery.add(query.and(query.criteria("id").equal(fruit.getId()), query.criteria("categories").equal(fruit.getCategories())));
 }

下面的查询 $matches 查询过滤器和 $unwinds categories 后跟 $group 删除重复项和排序。最后一步是从分组阶段和 $project 读取值到类别字段。

 List<Category> categories = new ArrayList<>();
  datastore.createAggregation(Fruits.class)
        .match(query)
        .unwind("categories")
        .group(Group.id(Group.grouping("categories")))
        .sort(Sort.ascending("_id.categories"))
        .project(Projection.projection("_id").suppress(), Projection.projection("category", "_id.categories"))
        .aggregate(Category.class).forEachRemaining(categories::add);


class Category {
    private String category;
}

更新:

Mongo Shell 查询

   [{ "$match" : { "$or" : [ { "$and" : [ { "_id" : 1234566} , { "categories" : [ "A" , "B" , "C" , "D"]}]} , { "$and" : [ { "_id" : 32434} , { "categories" : [ "A" , "C" , "E" , "F"]}]} , { "$and" : [ { "_id" : 32434} , { "categories" : [ "A" , "L" , "M" , "N"]}]}]}}, { "$unwind" : "$categories"}, { "$group" : { "_id" : { "categories" : "$categories"}}}, { "$sort" : { "_id.categories" : 1}}, { "$project" : { "_id" : 0 , "category" : "$_id.categories"}}]