我有一个对象的List
,我需要在Morphia
中执行查询才能从给定对象中的List
的另一个String
嵌入中获得唯一的结果。
对象类别:
@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
中的数据不可用,我需要在aggregation
(签出JSON格式)本身上应用fruitList
。 最佳答案
您可以使用以下代码通过聚合管道来获取唯一和排序类别。
准备查询过滤器:
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"}}]
关于java - 如何在吗啡中进行聚集?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43617897/