Mongodb匹配或类似查询

时间:2017-06-22 13:28:36

标签: java regex mongodb spring-boot mongodb-query

我有mongodb中的文档列表,如

{
        "id": "5948b044ef91edb15d222794",
        "articleId": "4",
        "author": "asdfghjkl",
        "publicationDate": 1454371200000,
        "rating": 4,
        "numViews": 600000,
        "summary": "In the end, bombastic bozo Donald Trump’s predictions of an Iowa victory were all a big, sad joke.",
        "articleUrl": "http://www.asdfghjkl.com/news/politics/donald-trump-predicts-iowa-victory-voters-caucusing-article-1.2516776",
        "keywords": [
            "Trump",
            "Election"
        ],
        "imgPath": [
            "http://assets.asdfghjkl.com/polopoly_fs/1.2516971.1454384425!/img/httpImage/image.jpg_gen/derivatives/article_1200/usa-election-trump.jpg"
        ],
        "articleName": "Ted Cruz, after trailing in polls, beats Donald Trump in Iowa caucus; Marco Rubio finishes a close third"
    }

我有一个关键字列表(像["特朗普","唐纳德""选举"]等字符串)我希望与{{{这些文档中有1}}和keywords列。

那么,如何在java spring-boot ??

中使用articleName从集合中获取匹配的文档

2 个答案:

答案 0 :(得分:1)

@Autowired
private MongoTemplate mongoTemplate;

Query query = new Query();
List<String> list = Arrays.asList("Trump", "Election");
query.addCriteria(Criteria.where("keywords").in(list));
List<YourModel> yourModel = mongoTemplate.find(query, YourModel.class);

答案 1 :(得分:0)

我是通过使用$ regex实现的:

BasicQuery query = new BasicQuery("{ keywords: { $regex: '(?:[\\s]|^)("+keywords+")(?=[\\s]|$)',$options: 'i' } } ");
  articlesList = mongoTemplate.find(query, Articles.class);

其中关键字如下:keyword1 | keyword2 | keyword3