如何在吗啡中进行聚合?
问题描述:
我有一个List
的对象,我需要在Morphia
中执行查询,以获得String
在给定对象中的另一个嵌入List
的唯一结果。如何在吗啡中进行聚合?
对象类:
@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]
的输出是以排序的形式。我如何在吗啡中实现这一点?我试图搜索官方文档,但无法找到提示。
任何帮助或提示将是可观的。由于
EDIT-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);
,我已经在fruitList
创建
class Category {
private String category;
}
数据是不可用的,我需要在fruitList
申请aggregation
(签出JSON格式)本身。
答
您可以使用下面的代码使用聚合管道获取唯一的&排序类别。
准备查询过滤器:
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;
}
更新:
蒙戈壳牌查询
[{ "$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"}}]
谢谢您的回答。 '_id'在这里指'Fruits.id'。对? –
不客气。没有它从'group'生成的'_id'。添加了Mongo shell查询用于比较,并在帖子中添加了一些解释。 – Veeram
我想实现这个代码,但是对于在哪里以及如何在上面的代码中使用'Fruit'对象数据感到困惑。你能帮我出来吗?我的意思是如何在上面的Json上应用这个聚合查询? –