如果我有一个文件的定义为
[
{
"title": "title",
"tags": [ "cool", "amazing", "funny" ]
},
{
"title": "another title",
"tags": [ "nice", "amazing", "funny" ]
}
]
我想要能够查询与MongoTemplate为了通过列表的价值观,如["酷","惊人的"],并在返回的第一个收集上,而不是第二次。 为什么我的意思是实现, 美元 的条件似乎不够的。 我试图与 $所有 条件,从Mongo控制台,它的工作因为我需要的,但在我的代码什么不工作和它永远对我的查询,以阐述。 用 美元 操作我的代码转速度快,而不是。 我的方法在我的储存库(由于其他原因,我必须做的一个聚合作下):
public Page<MyDocument> findByProperties(String title, List<ObjectId> tags, Pageable page) {
final List<Criteria> criteria = new ArrayList<>();
Aggregation aggregation = null;
if (title != null && !title.isEmpty()) {
criteria.add(Criteria.where("title").is(title));
}
if (tags != null && !tags.isEmpty()) {
criteria.add(Criteria.where("MyBook.tags").all(tags));
}
if (!criteria.isEmpty()) {
aggregation = Aggregation.newAggregation(
Aggregation.lookup("from_collection", "_id", "idParent", "MyBook"),
Aggregation.unwind("MyBook"),
Aggregation.match(new Criteria().andOperator(criteria.toArray(new Criteria[0]))),
Aggregation.skip(page.getOffset()),
Aggregation.limit(page.getPageSize()),
Aggregation.sort(page.getSort())
);
} else {
aggregation = Aggregation.newAggregation(
Aggregation.lookup("from_collection", "_id", "idParent", "MyBook"),
Aggregation.unwind("MyBook"),
Aggregation.skip(page.getOffset()),
Aggregation.limit(page.getPageSize()),
Aggregation.sort(page.getSort())
);
}
List<MyDocument> results = mongoTemplate.aggregate(aggregation, "my_document", MyDocument.class).getMappedResults();
return PageableExecutionUtils.getPage(results, page,
() -> (long)results.size());
}
看看 这个 回答的,我试过
criteria.add(Criteria.where("MyBook.tags").in(tags).all(tags));
但什么都没有改变,查询需要永远和不与期望输出。 任何想法吗? 谢谢你!