2017-05-05 68 views
0

我想检索一样,如果我给2017年2月1日0时05分46秒前两个字符值,我应该得到类似结果MongoDB的Java驱动程序取回前两个字符

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

没有串SyTime_000_09_00:00

我使用jongo库和蒙戈驱动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 " 
} 

这是我曾尝试

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); 
    } 
} 

这里是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; 
    } 

}

我使用JFrame的按钮操作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

+0

基于此示例,您希望检索第一个空格之前的字符串。它是否正确? –

+0

如果你使用'Pattern.compile(“02-01-2017 [0-9:] +”);'?我猜这会返回所有*条目*,并且只需要匹配,对吧? –

+0

我想只在我的Jlist中显示结果“02-01-2017 00:05:46”没有字符串现在我得到了像我这样的结果“02-01-2017 00:05:46 SyTime_000_09_00:00”你也可以看看结果图像,我想在它到达Jlist之前进行修剪。 @WiktorStribiżew –

回答

0

正如WiktorStribiżew所述

p.getData()返回一个被添加到listModel的字符串。使用p.getData()。replaceFirst(“^(\ S + \ s \ S +)。*”,“$ 1”)