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)
问题是如果我想搜索猫,我需要先将投影放在管道中但是如果我想要文本那么我需要首先匹配。我有什么方法可以做到吗?
答案 0 :(得分:1)
毕竟这是一个非常简单的解决方案。
我创建了一个新的标准对象
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)