简体   繁体   中英

MongoDB java driver using regex query to retrieve first two character

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 

Without string SyTime_000_09_00:00

i am using jongo library and mongo drive 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

   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

      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

结果

As stated by Wiktor Stribiżew

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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