更新:原创答案(底部)向您展示如何按年份排序(OP问如何得到一年,所以我认为他们是如何排序的)。这是如何按日期排序:
要么改变insert_ts
场是一个日期,或添加新的字段是一个日期,例如:
Date insertTsDate = null;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy-hh-mm-ss-SS");
try {
insertTsDate = dateFormat.parse(insert_ts);
}
catch (Exception e) {
// handle exception
}
然后将新字段添加到您的文档所谓insert_ts_date
(或任何你想将它命名),它上面设置为insertTsDate
变量,有点像这样:
List<Map<String, String>> sortDocument = new ArrayList<Map<String, String>>();
Map<String, String> sortByInsertTsDate = new HashMap<String, String>();
sortByInsertTsDate.put("insert_ts_date", "asc");
sortDocument.add(sortByInsertTsDate);
原来的答案:
我认为你将不得不明确地添加一年属性到你的文档。如果你有一年,那么只需将它添加到你的文档。如果您需要从字符串解析它,你可以使用正则表达式或日期/日历类分析日期:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy-hh-mm-ss-SS");
try {
Date date = dateFormat.parse(insert_ts);
Calendar c = Calendar.getInstance();
c.setTime(date);
int year = c.get(Calendar.YEAR);
}
catch (Exception e) {
// handle exception
}
然后发出您的查询,如下所示:
List<Map<String, String>> sortDocument = new ArrayList<Map<String, String>>();
Map<String, String> sortByYear = new HashMap<String, String>();
sortByYear.put("year", "asc");
sortDocument.add(sortByYear);
请JSON数据共享 –
@ Ahmd我的数据库中有“_id”:“0c7c-5d47-ec66”,“_rev”:“2-534bc2bc2bc4014a9884052cd2d0551e”,“device_id”:“BT:DEMO”,“user_id”:“0c7c-5d47” “insert_ts”:“11-Jul-2014-07-59-41-34”如果我想对insert_ts进行排序,那么我如何从字符串中获得年份? –