gpt4 book ai didi

java - MongoDB Java 驱动程序聚合框架使用 $match 和 $text $search 但首先需要 $project

转载 作者:行者123 更新时间:2023-11-30 06:43:12 24 4
gpt4 key购买 nike

docs注意:

要在 $match 阶段使用 $text,$match 阶段必须是管道的第一个阶段。

一些 JSON 示例:

{"pid":"b00l16vp", "title": "in our time","categories":{"category1":["factual", "arts culture and the media", "history"]}}
{"pid":"b0079mpp", "title": "doctor who", "categories":{"category2":["childrens", "entertainment and comedy", "animation"],"category1":["signed"]}}
{“pid":"b00htbn3"}
{“pid":"b00gdhqw","categories":{"category2":["factual"],"category3":["scotland"],"category4":["lifestyle and leisure", "food and drink"],"category1":["entertainment", "games and quizzes"]}}

我有以下查询:

    List<BasicDBObject> pipeline = new ArrayList<>()
BasicDBObject criteria = new BasicDBObject()
BasicDBObject theProjections = new BasicDBObject()
AggregateIterable iterable

//value is coming from a parameter
if (value != null) {
//a text index has been created on the title field
criteria.put('$text', new BasicDBObject('$search', value))

}
//cats is coming from a parameter but it will be an array of Strings
if (cats.length != 0) {

ArrayList<BasicDBObject> orList = new ArrayList<>()
ArrayList<BasicDBObject> andList = new ArrayList<>()
BasicDBList theMegaArray = new BasicDBList()


for (int i = 1; i <= 5; i++) {

String identifier = "categories.category" + i
String cleanIdentifier = '$' + identifier
//If the category does not exist, put in a blank category
theMegaArray.add(new BasicDBObject('$ifNull', Arrays.asList(cleanIdentifier, Collections.EMPTY_LIST)))
}
//merges all of the category arrays into 1
theProjections.put("allCategories", new BasicDBObject('$setUnion', theMegaArray))
orList.add(new BasicDBObject("allCategories", new BasicDBObject('$all', cats)))

andList.add(new BasicDBObject('$or', orList))
criteria.put('$and', andList)
}
pipeline.add(new BasicDBObject('$project', theProjections))
pipeline.add(new BasicDBObject('$match', criteria))


//and by default
iterable = collection.aggregate(pipeline)

问题是,如果我想搜索猫,我需要首先将投影放在管道中,但如果我想要文本,那么我需要先将匹配放在管道中。有什么办法可以两者兼得吗?

最佳答案

这毕竟是一个非常简单的解决方案。

我创建了一个新的条件对象

BasicDBObject criteriaCat = new BasicDBObject()

添加了类别,而不是原来的标准。

criteriaCat.put('$and', andList)

将 $match 首先放入管道中,然后放入 $project,如果有猫,则再次对结果运行 $match。

 pipeline.add(new BasicDBObject('$match', criteria))
pipeline.add(new BasicDBObject('$project', theProjections))

if (cats.length != 0) {
pipeline.add(new BasicDBObject('$match', criteriaCat))
}
pipeline.add(new BasicDBObject('$sort', sorting))

//and by default
iterable = collection.aggregate(pipeline)

关于java - MongoDB Java 驱动程序聚合框架使用 $match 和 $text $search 但首先需要 $project,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44068620/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com