【发布时间】:2018-07-10 14:24:22
【问题描述】:
我想在 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 个文档,“type”为“football”和“team”,如 barcelona
{"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"}
提前谢谢你。
【问题讨论】:
-
正则表达式适用于文本字段。因此,数字字段上没有正则表达式“喜欢”。顺便说一句,使用范围 max 和 min 怎么样?介于 250 - 250 之间(填充零 - 与最大双精度类型值一样多的零)或将薪水字段存储为字符串类型。
-
我不能使用范围,因为当我输入 250 时,我想要 250、2500、25000 范围内的所有匹配记录......等等。由于一些算术运算,甚至我也无法将薪水设为字符串。顺便说一句,感谢您的评论。还有其他可能的解决方案吗?
-
哦,我明白了。 NP。您可以将 250 的所有组合作为 $in 标准传递。我没有看到任何其他解决方案。
-
@Sumanth Varada 您可以使用“$eq”运算符进行精确匹配。前任。 db.players.find( { 薪水: { $eq: 25000 } } );
-
@RahulGhadage 我正在使用如下的弹簧数据标准。您能否更正以下标准。 query.addCriteria(Criteria.where("slary").is(salary));
标签: mongodb spring-boot