【问题标题】:Filtering a string filed against a string list in mongo db根据 mongo db 中的字符串列表过滤字符串
【发布时间】:2020-02-24 06:30:18
【问题描述】:

尝试使用字符串字段对字符串列表过滤集合。

public List<Case> getCases(List<String> doctorIds) {

 Query query = new Query();
 query.addCriteria(Criteria.where("primaryDoctorId").in(doctorIds));
 return mongoTemplate.find(query, Case.class);

} 

过滤mongo类

public class Case {

   private String primaryDoctorId;

    public String getPrimaryDoctorId() {
    return primaryDoctorId;
   }

   public void setPrimaryDoctorId(String primaryDoctorId) {
    this.primaryDoctorId = primaryDoctorId;
  }

}

但这并没有按预期工作,即使有满足此条件的记录。

【问题讨论】:

    标签: java mongodb mongodb-query


    【解决方案1】:

    您可以尝试使用BasicDBObjectBasicDBList 构建查询过滤器

    public List < Case > getCases(List < String > doctorIds) {
        BasicDBList docIds = new BasicDBList();
        docIds.addAll(doctorIds);
        DBObject inClause = new BasicDBObject("$in", docIds);
        DBObject query = new BasicDBObject("primaryDoctorId", inClause);
    
        MongoCursor < Document > cursor = collection.find(query).iterator();
        try {
            while (cursor.hasNext()) {
                System.out.println(cursor.next().toJson());
            }
        } finally {
            cursor.close();
    
        }
    }
    

    【讨论】:

      【解决方案2】:

      以下代码可以正常工作。我创建了一个包含几个文档的集合; “案例”集合:

      { "_id" : ObjectId("5e539c699753e47a7525da78"), "primaryDoctorId" : "1", "other" : "str-1" }
      { "_id" : ObjectId("5e539c729753e47a7525da79"), "primaryDoctorId" : "2", "other" : "str-2" }
      

      Spring Mongo Java 代码:

      MongoOperations mongoOps = new MongoTemplate(MongoClients.create(), "test");
      List<String> docIds = Arrays.asList("1", "3", "5");
      Query qry = new Query(Criteria.where("primaryDoctorId").in(docIds));
      List<Case> list = mongoOps.find(qry, Case.class);
      list.forEach(System.out::println);
      

      输出返回:"1"

      Case.java:

      请注意,我添加了toString() 方法,以便输出打印primaryDoctorId

      public class Case {
      
          private String primaryDoctorId;
      
          public String getPrimaryDoctorId() {
              return primaryDoctorId;
         }
      
          public void setPrimaryDoctorId(Stringint primaryDoctorId) {
              this.primaryDoctorId = primaryDoctorId;
        }
      
          @Override
          public String toString() {
              return "docId: " + primaryDoctorId;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-14
        • 2011-01-10
        • 2015-05-08
        • 2012-12-06
        • 1970-01-01
        • 1970-01-01
        • 2013-11-25
        相关资源
        最近更新 更多