下面列出了com.mongodb.DBCursor#sort ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public List<GridFSDBFile> findAll(OrderBy orderBy, Page page) {
DBCursor _cursor = __dbCollection.find();
if (orderBy != null) {
_cursor.sort(orderBy.toBson());
}
if (page != null && page.page() > 0 && page.pageSize() > 0) {
_cursor.skip((page.page() - 1) * page.pageSize()).limit(page.pageSize());
}
List<GridFSDBFile> _results = new ArrayList<GridFSDBFile>();
while (_cursor.hasNext()) {
_results.add((GridFSDBFile) _cursor.next());
}
_cursor.close();
return _results;
}
@Override
public List<GridFSDBFile> find(Query query, OrderBy orderBy, Page page) {
DBCursor _cursor = __dbCollection.find(query.toBson());
if (orderBy != null) {
_cursor.sort(orderBy.toBson());
}
if (page != null && page.page() > 0 && page.pageSize() > 0) {
_cursor.skip((page.page() - 1) * page.pageSize()).limit(page.pageSize());
}
List<GridFSDBFile> _results = new ArrayList<GridFSDBFile>();
while (_cursor.hasNext()) {
_results.add((GridFSDBFile) _cursor.next());
}
_cursor.close();
return _results;
}
/**
* Find all DBObjects from database using this query.
* Note 1: it may do a full table scan if the query contains no index keys.
* Note 2: it will fetch all content into JVM memory rather than use lazy loading.
* So make sure you call it only at small collection such as configuration data.
*
* @param query
* @param databaseName
* @param namespace
* @param collection
* @param fields
* @return
*/
public static final List<DBObject> queryAllFromMongo(DBObject query,
String databaseName, String namespace, String collection,
DBObject fields, DBObject sortFields) {
DBCollection coll = getDBCollection(databaseName, namespace, collection);
int count = (int)coll.count(query);
ArrayList<DBObject> objList = new ArrayList<DBObject>();
DBCursor list = coll.find(query, fields);
if ( sortFields != null ) {
list = list.sort(sortFields);
}
while ( list.hasNext() ) {
objList.add(list.next());
}
return objList;
}
/**
* Find all DBObjects from database using this query.
* Note 1: it may do a full table scan if the query contains no index keys.
* Note 2: it will fetch all content into JVM memory rather than use lazy loading.
* So make sure you call it only at small collection such as configuration data.
*
* @param query
* @param databaseName
* @param namespace
* @param collection
* @param fields
* @return
*/
public static final List<DBObject> queryAllFromMongo(DBObject query,
String databaseName, String namespace, String collection,
DBObject fields, DBObject sortFields, int numToSkip, int limit) {
DBCollection coll = getDBCollection(databaseName, namespace, collection);
int count = (int)coll.count(query);
ArrayList<DBObject> objList = new ArrayList<DBObject>();
DBCursor list = coll.find(query, fields).skip(numToSkip).limit(limit);
if ( sortFields != null ) {
list = list.sort(sortFields);
}
while ( list.hasNext() ) {
objList.add(list.next());
}
return objList;
}
/**
* Find all DBObjects from database using this query.
* Note 1: it may do a full table scan if the query contains no index keys.
* Note 2: it will fetch all content into JVM memory rather than use lazy loading.
* So make sure you call it only at small collection such as configuration data.
*
* @param query
* @param databaseName
* @param namespace
* @param collection
* @param fields
* @return
*/
public static final List<DBObject> queryAllFromMongo(DBObject query,
String databaseName, String namespace, String collection,
DBObject fields, DBObject sortFields) {
DBCollection coll = getDBCollection(databaseName, namespace, collection);
//int count = (int)coll.count(query);
ArrayList<DBObject> objList = new ArrayList<DBObject>();
DBCursor list = coll.find(query, fields);
if ( sortFields != null ) {
list = list.sort(sortFields);
}
while ( list.hasNext() ) {
objList.add(list.next());
}
return objList;
}
/**
* Find all DBObjects from database using this query.
* Note 1: it may do a full table scan if the query contains no index keys.
* Note 2: it will fetch all content into JVM memory rather than use lazy loading.
* So make sure you call it only at small collection such as configuration data.
*
* @param query
* @param databaseName
* @param namespace
* @param collection
* @param fields
* @return
*/
public static final List<DBObject> queryAllFromMongo(DBObject query,
String databaseName, String namespace, String collection,
DBObject fields, DBObject sortFields, int numToSkip, int limit) {
DBCollection coll = getDBCollection(databaseName, namespace, collection);
int count = (int)coll.count(query);
ArrayList<DBObject> objList = new ArrayList<DBObject>();
DBCursor list = coll.find(query, fields).skip(numToSkip).limit(limit);
if ( sortFields != null ) {
list = list.sort(sortFields);
}
while ( list.hasNext() ) {
objList.add(list.next());
}
return objList;
}
public DBCursor selectSet(DBCollection collection) {
DBObject fields = getFields();
DBObject query = getQuery();
DBObject orderByObject = getOrderByObject();
DBCursor cursor = null;
// 日志
log(fields, query, orderByObject);
if (null != query && null == fields) {
cursor = collection.find(query);
} else if (null == query && null != fields) {
cursor = collection.find(new BasicDBObject(), fields);
} else if (null != fields && null != query) {
cursor = collection.find(query, fields);
} else {
cursor = collection.find();
}
if (null != orderByObject) {
cursor.sort(orderByObject);
}
if (null != this.limit) {
if (null == this.limit.getOffset()) {
cursor.limit(this.limit.getRowCount());
} else {
cursor.limit(this.limit.getRowCount());
cursor.skip(this.limit.getOffset());
}
}
return cursor;
}
@Override
protected DBCursor getDataCursor(Map<String, ?> ranges, int start, int count, ColumnDescriptor[] columnDescriptors, Map<String, INDEXTYPE> indexTypes) {
DBCursor cursor = super.getDataCursor(ranges, start, count, columnDescriptors, indexTypes);
//TODO use indexes on filters ; check http://emptysqua.re/blog/optimizing-mongodb-compound-indexes/
// example : {horizon:1,datetime:1,CHOO17GROUP_1_NGU_SM_P:1}
return cursor.sort(new BasicDBObject("datetime", 1));
}
@Override
protected DBCursor getDataCursor(Map<String, ?> ranges, int start, int count, ColumnDescriptor[] columnDescriptors, Map<String, INDEXTYPE> indexTypes) {
DBCursor cursor = super.getDataCursor(ranges, start, count, columnDescriptors, indexTypes);
return cursor.sort(new BasicDBObject("datetime", 1));
}
@Get("csv|json")
public Object getRepresentation() {
if (ds == null) {
getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
return null;
}
if (!ds.getStatus().isInitialized()) {
getResponse().setStatus(Status.SUCCESS_ACCEPTED);
return "Initializing...";
}
Form queryForm = getRequest().getOriginalRef().getQueryAsForm();
ITeslaDatasource teslaDs = (ITeslaDatasource)ds;
String fieldName = (String)getRequest().getAttributes().get("field");
if (fieldName != null) {
if ("regions".equals(fieldName))
return teslaDs.getMetadata().getRegions();
else if ("count".equals(fieldName)) {
DBCursor cursor = getData().getCursor();
cursor.sort(null);
return ((Number)cursor.explain().get("n")).intValue();
}
else if ("forecastsDiff".equals(fieldName))
return getForecastsAndSnapshots();
else if ("stations".equals(fieldName))
return teslaDs.getMetadata().getToposPerSubstation().keySet();
else if ("explain".equals(fieldName))
return new JsonRepresentation(((MongoDataset)getData()).explain().toString());
else if ("countries".equals(fieldName))
return teslaDs.getMetadata().getCountries();
else if ("topos".equals(fieldName)) {
//warn this is potentially a large result - must implement a finer query mechanism (per substation id)
String stationId = queryForm.getFirstValue("topoId", true);
if (stationId == null) {
return teslaDs.getMetadata().getToposPerSubstation();
}
else return teslaDs.getMetadata().getToposPerSubstation().get(stationId).keySet();
}
else return null;
} else
return super.getRepresentation();
}
public List<PrivateStorage> findByQuery(String collectionName,
Map<String, String> queryParam,
String sort,
int pageNumber,
int pageSize) throws JsonProcessingException {
List<BasicDBObject> criterias = queryParam.entrySet()
.stream()
.map(item -> {
String[] params = item.getValue().split(":");
String value = params[0];
FilterEnum filter = FilterEnum.DEFAULT;
if (params.length == 2) {
String operator = params[0];
value = params[1];
filter = FilterEnum.valueOf(operator.toUpperCase());
}
return filter.criteria(item.getKey(), value);
})
.collect(Collectors.toList());
List<PrivateStorage> privatesStorage = new ArrayList<>();
DBObject query = new BasicDBObject();
if (!criterias.isEmpty()) {
List<BasicDBObject> andCriteria = new ArrayList<>();
andCriteria.addAll(criterias);
query.put("$and", andCriteria);
}
DBCollection collection = mongoPrivateStorageTemplate.getCollection(collectionName);
DBCursor cursor = collection.find(query);
if (sort != null) {
String[] sortParams = sort.split(":");
BasicDBObject sortObject = SortEnum.valueOf(sortParams[0].toUpperCase()).sort(sortParams[1]);
cursor.sort(sortObject);
}
toPrivateStorageList(collectionName, privatesStorage, cursor, pageNumber, pageSize);
return privatesStorage;
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*
* Get resource
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (mDS != MongoService.getInstance()) {
System.out.println("MongoService db name is changed");
mDS = MongoService.getInstance();
mCollRef = mDS.getCollection("refpoints");
mCollSamp = mDS.getCollection("samplings");
mCollMap = mDS.getCollection("maps");
}
String type = request.getParameter("type");
String id = request.getParameter("id");
System.out.println("doGet: type=" + type + " id=" + id);
if ("file".equals(type)) {
if (id == null) {
// Get list of files
mDS.sendJSON(mDS.getFileList(), request, response);
return;
}
try {
mDS.sendFile(id, response);
} catch (Exception e) {
System.err.println("Send error: " + id);
}
return;
}
// Get document(s)
String distinct = request.getParameter("distinct");
String pipeline = request.getParameter("pipeline");
String query = request.getParameter("query");
String keys = request.getParameter("keys");
String format = request.getParameter("format");
DBObject queryObj = query != null ? (DBObject) JSON.parse(query) : null;
DBObject keysObj = keys != null ? (DBObject) JSON.parse(keys) : null;
Object result = null;
DBCollection collection = mDS.getCollection(type);
if (id != null) {
result = collection.findOne(new ObjectId(id), keysObj);
} else if (distinct != null) {
result = collection.distinct(distinct, queryObj);
} else if (pipeline != null) {
DBObject pipelineObj = (DBObject) JSON.parse(pipeline);
if (pipelineObj instanceof List<?>) {
result = collection.aggregate((List<DBObject>) pipelineObj).results();
} else {
result = collection.aggregate(pipelineObj).results();
}
} else {
DBCursor cursor = collection.find(queryObj, keysObj);
String sort = request.getParameter("sort");
String skip = request.getParameter("skip");
String limit = request.getParameter("limit");
String count = request.getParameter("count");
if (sort != null) {
cursor = cursor.sort((DBObject) JSON.parse(sort));
}
if (skip != null) {
cursor = cursor.skip(Integer.parseInt(skip));
}
if (limit != null) {
cursor = cursor.limit(Integer.parseInt(limit));
}
result = "true".equals(count) ? cursor.count() : cursor;
}
if (id != null && result == null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, String.format("Document %s does not exist", id));
return;
}
if ("csv".equals(format)) {
mDS.sendCSV(result, request, response);
return;
}
mDS.sendJSON(result, request, response);
}