'MongoDB search using multiple field in a Spring Boot project
I'm working in a Spring project and I need to search using different fields for example: id, username, city, country, company, phonenumber ...
It's obvious that I don't need to write a method like: studentRepository.findByIdAndUsernameAndCityAnd...
What I need exactly is the correspondent SQL query in MongoDB.
@Query("Select stu from Student stu
where (stu.entreprise.radical in ?6)
and (?1 is null or stu.status=?1)
and (?2 is null or stu.dateValidity=?2)
and (?3 is null or stu.montant=?3)
and (?4 is null or stu.devise=?4)
and (?5 is null or stu.referenceClient=?5)
order by stu.createdAt desc" )
Solution 1:[1]
Should work like this:
db.collection.find({
radical: {
$in: [
<value1>,
<value2>,
...,
<valueN>
]
},
$and: [
{
$or: [
{
status: null
},
{
status: <value>
}
]
},
{
$or: [
{
validity: null
},
{
validity: <value>
}
]
},
{
$or: [
{
montant: null
},
{
montant: <value>
}
]
},
{
$or: [
{
devise: null
},
{
devise: <value>
}
]
},
{
$or: [
{
referenceClient: null
},
{
referenceClient: <value>
}
]
}
]
},
{})
.sort({createdAt: -1})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Oli |
