简体   繁体   English

如何在spring中的mongoDB中查询过滤

[英]How to Query and filter in mongoDB in spring

I want to search my recipes by tags that are array of Strings and want to filter by tags我想按字符串数组的标签搜索我的食谱,并希望按标签过滤

I know it will be我知道会

db.Recipe.find({$and:[{tags:"Desert"},{tags:"low-fat"}]}).pretty() db.Recipe.find({$and:[{tags:"Desert"},{tags:"low-fat"}]}).pretty()

but I do not know how to write the query in java spring to be flexible flexible means numbers of filtered options can be vary但我不知道如何在 java spring 中编写查询以灵活灵活意味着过滤选项的数量可以变化

Autowired the MongoTemplate自动装配 MongoTemplate

@Autowired
MongoTemplate mongoTemplate;

Then use your filter inside the andOperator()然后在andOperator()中使用您的过滤器

public void somemethod(){
    Query query=Query.query( new Criteria().andOperator(
        Criteria.where("tags").is("Desert"),
        Criteria.where("anotherFilter").is("answer"),
        // write more filter
        )
    );

    List<Recipe> =mongoTemplate.find(query,Recipe.class);
    // do your stuffs
}

we can get the list of tags from client then search it by that tags我们可以从客户端获取标签列表,然后通过该标签进行搜索

@GetMapping("/recipe/searchByTags/{tags}") @GetMapping("/recipe/searchByTags/{tags}")

public List<Recipe> getRecipesByTags(@PathVariable List<String> tags){
    Query query =  Query.query(
            Criteria.where("tags").all(tags)
    );
    return  mongoTemplate.find(query,Recipe.class);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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