简体   繁体   中英

Springboot: How to execute custom mongodb query by springboot?

I want to find a list of models matched either field nameEnglish or nameChinese by a keyword. I spent more than an hour googling but I cannot do it. Please help.

Springboot Mongo starter example https://spring.io/guides/gs/accessing-data-mongodb/

The custom query I want to execute and return a list result

db.mymodel.aggregate([ 
    {
        $match: {
            $or :[
             { nameChinese: /門/ },
             { nameEnglish: /cocina/i }
            ]
        }
    },
    { $sort: {nameEnglish: 1} }
])

My best trial so far

interface MyModelRepository : MongoRepository<MyModel, String> {
    @Query(value = "{ '\$match': { \$or: [ {'nameEnglish': { \$regex: ?0 } }, {'nameChinese': { \$regex: ?0 } } ] }")
    fun findByMyQuery(name: String): List<MyModel>
}

For the regex, I also want it to be case insensitive.

I found the answer after a hot water shower ( and one day of googling and reading documents). Hope this help someone in the future.

@Query(value = "{ \$or: [ {'nameEnglish': { \$regex: ?0, \$options: 'i'}}, {'nameChinese': { \$regex: ?0 }}] }", sort = "{nameEnglish: 1}")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM