我想在Spring Boot中对Integer/Double字段进行LIKE查询。
收藏名称:球员
{
"firstName" : "Lionel",
"lastName" : "messi",
"team" : "FC Barcelona",
"salary" : 40000,
"type" : "football"
},{
"firstName" : : "Cristiano",
"lastName" : "Ronaldo",
"team" : "Real Madrid C.F.",
"salary" : 35000,
"type" : "football"
},{
"firstName" : : "Neymar",
"lastName" : "Jr",
"team" : "Paris Saint-Germain F.C.",
"salary" : 25000,
"type" : "football"
},{
"firstName" : "Luis",
"lastName" : "Alberto",
"team" : "FC Barcelona",
"salary" : 25000,
"type" : "football"
},{
"firstName" : "Virat",
"lastName" : "Kohali",
"team" : "Indian Cricket Team",
"salary" : 40000,
"type" : "cricket"
}
并且我的spring java代码如下,其中生成查询.
String game = "football";
String team = "barcelona";
Double salary = 250;
Query query = new Query();
Set<String> gameType = new HashSet<>();
List<Criteria> andCriteria = new ArrayList<>();
gameType.add(game);
andCriteria.add(Criteria.where("type").in(gameType));
andCriteria.add(Criteria.where("team").regex(team,"i"));
Criteria[] criteriaArray = new Criteria[andCriteria.size()];
criteriaArray = andCriteria.toArray(criteriaArray);
query.addCriteria(new Criteria().andOperator(criteriaArray));
List<Players> players = mongoTemplate.find(query, Players.class);
return players;
质询:
db.players.find({
$and: [{
"type": {
$in: ["football"]
}
},
{
"team": {
$regex: "barcelona",
$options: "i"
}
}]
})
上面的查询返回了2个文档,"类型"为"足球"和"球队",如 * 巴塞罗那 *
{"firstName" : "Lionel", "lastName" : "messi", "team" : "FC Barcelona", "salary" : 40000, "type" : "football"},
{"firstName" : "Luis", "lastName" : "Alberto", "team" : "FC Barcelona", "salary" : 25000, "type" : "football"}
但我希望查询"类型"为"足球","工资"为 * 250 *
db.players.find({
$and: [{
"type": {
$in: ["football"]
}
},
{
$where : "/^250.*/.test(this.salary)"
}]
})
并且返回的结果将如下。
{"firstName" : : "Neymar", "lastName" : "Jr", "team" : "Paris Saint-Germain F.C.", "salary" : 25000, "type" : "football"},
{"firstName" : "Luis", "lastName" : "Alberto", "team" : "FC Barcelona", "salary" : 25000, "type" : "football"}
先谢谢你。
2条答案
按热度按时间ffscu2ro1#
我设法建立双字段的LIKE查询。
这段代码生成了我上面发布的LIKE。
你也可以用简单的方法来做。
质询:
我希望这会有所帮助。
j9per5c42#
根据@Rahul Ghadage的回答,我能够让这个工作:
注意,代码示例中的salary是用要匹配的数字填充的Java变量,第二个salary是mongo结构中字段的名称。