[英]MongoTemplate method or query for finding maximum values from a fileds
[英]MongoTemplate Query array that match at least the values I'm passing
如果我將文檔定義為
[
{
"title": "title",
"tags": [ "cool", "amazing", "funny" ]
},
{
"title": "another title",
"tags": [ "nice", "amazing", "funny" ]
}
]
我希望能夠使用 MongoTemplate 進行查詢,以便傳遞像 ["cool","amazing"] 這樣的值列表,並返回上面的第一個集合,而不是第二個集合。 對於我要實現的目標, $in條件似乎還不夠。 我嘗試了$all條件,並從 Mongo 控制台按我的需要工作,但在我的代碼中有些東西不起作用,我的查詢需要很長時間才能詳細說明。 使用$in運算符,我的代碼運行得很快。 我在我的存儲庫中的方法(出於其他原因,我必須進行如下聚合):
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));
但是沒有任何改變,查詢需要永遠,而不是預期的 output。 請問有什么想法嗎? 謝謝!
要查找 tags 數組字段是否包含 youe 數組的所有成員,您可以使用波紋管,如果您需要它在聚合管道中使用第二個。
在您的查詢中,您有更多階段和更多代碼,如果您想詢問更多是否可以提供示例數據和 JSON 中的預期 output,以及您想做什么,以便人們可以提供幫助。
查詢1
$all
運算符查找db.collection.find({"tags": {"$all": ["cool","amazing"]}})
查詢2
aggregate(
[{"$match":
{"$expr":
{"$eq": [{"$setDifference": [["cool", "amazing"], "$tags"]}, []]}}}])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.