MongoDB java驱动程序使用正则表达式查询来检索前两个字符

时间:2021-04-14 03:03:21

i want to retrieve first two character value like if i give 02-01-2017 00:05:46 i should get result like

我想检索前两个字符值,如果我给02-01-2017 00:05:46我应该得到结果像

02-01-2017 00:05:46 
02-01-2017 00:05:46 
02-01-2017 00:05:46 

Without string SyTime_000_09_00:00

没有字符串SyTime_000_09_00:00

i am using jongo library and mongo drive 3.4.2

我正在使用jongo库和mongo驱动器3.4.2

{
  "_id" : ObjectId("590b70c609200535e85c6540"),
  "Data" : "02-01-2017 00:05:46 SyTime_000_09_00:00 "
}
{
  "_id" : ObjectId("590b70c609200535e85c6541"),
  "Data" : "02-01-2017 00:05:46 DPMPow_P01_04_  45.53 "
}

Here is what i have tried

这是我尝试过的

public class DataSource {
  private MongoCollection collection;

  public void DataSource() {
    this.collection = (new Jongo(new
        MongoClient("localhost", 27017).getDB("admin"))).getCollection("test");
  }

  public void guarder(Object obj) {
    this.collection.save(obj);
  }

  public Iterable consol() {
    DBObject query = new BasicDBObject();

    Pattern regex = Pattern.compile("02-01-2017");
    query.put("Data", regex);
    return (Iterable) this.collection.find(query.toString()).as(pojo.class);
  }
}

here is pojo class

这是pojo课程

   public class pojo {
   @MongoObjectId 
   String _id;        
   String Data;


  public pojo() {

  }

   public pojo(String Data) {
    this.Data = Data;
   }


  public String getData() {
    return Data;
   }


   public String getId() {
    return _id;
   }

}

i am using jframe Button Action GUi

我正在使用jframe Button Action GUi

      private void findActionPerformed(java.awt.event.ActionEvent evt) {                                           

    try{

     DefaultListModel listModel = new DefaultListModel();
     DataSource ds=new DataSource(); 
     ds.DataSource();

        Iterable pojo=ds.consol();
        pojo p;
        int i=0;
        for (Iterator it=pojo.iterator();it.hasNext();){  
        p = (pojo)it.next();
         listModel.addElement(p.getData());

        }
      mdata.setModel(listModel); //jlist

    }catch(Exception e){
        System.out.println(e);

    }
} 

Result

MongoDB java驱动程序使用正则表达式查询来检索前两个字符

1 个解决方案

#1


0  

As stated by Wiktor Stribiżew

正如WiktorStribiżew所述

p.getData() returns a String that is added to the listModel. Use p.getData().replaceFirst("^(\S+\s\S+).*", "$1")

p.getData()返回添加到listModel的String。使用p.getData()。replaceFirst(“^(\ S + \ s \ S +)。*”,“$ 1”)

#1


0  

As stated by Wiktor Stribiżew

正如WiktorStribiżew所述

p.getData() returns a String that is added to the listModel. Use p.getData().replaceFirst("^(\S+\s\S+).*", "$1")

p.getData()返回添加到listModel的String。使用p.getData()。replaceFirst(“^(\ S + \ s \ S +)。*”,“$ 1”)