【问题标题】:Mongodb Match or Like QueryMongodb Match or Like 查询
【发布时间】:2017-11-25 19:35:59
【问题描述】:

我有 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"
    }

我有一个关键字列表(字符串,如 ["Trump","Donald","Election"]),我想与这些文档中的 keywordsarticleName 列进行匹配。

那么,如何在 java spring-boot 中使用 $in or $or or regex 从集合中获取匹配的文档??

【问题讨论】:

  • 使用spring数据!如果您希望人们帮助您,请付出一些努力。
  • 将您的@Repository 放入问题中,使用此信息实现的接口我们可以为您提供帮助

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


【解决方案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);

【讨论】:

    【解决方案2】:

    我已经通过使用 $regex 的实现来做到这一点:

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

    关键字是这样的:keyword1|keyword2|keyword3

    【讨论】:

      猜你喜欢
      • 2020-03-21
      • 2012-06-20
      • 2020-08-06
      • 2021-12-02
      • 2015-05-20
      • 2020-07-09
      • 2020-09-22
      • 2013-11-30
      • 1970-01-01
      相关资源
      最近更新 更多