本文整理匯總了Java中com.mongodb.client.FindIterable.sort方法的典型用法代碼示例。如果您正苦於以下問題:Java FindIterable.sort方法的具體用法?Java FindIterable.sort怎麽用?Java FindIterable.sort使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類com.mongodb.client.FindIterable
的用法示例。
在下文中一共展示了FindIterable.sort方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: findOne
import com.mongodb.client.FindIterable; //導入方法依賴的package包/類
/**
* 查詢一個
*
* @param collectionName 集合名
* @param query 查詢條件
* @param fields 返回字段或者排除字段
* @param sort
* @return
*/
public Map<String, Object> findOne(
String collectionName,
MongodbQuery query, MongodbFields fields, MongodbSort sort) {
MongoCollection<Document> collection = sMongoDatabase.getCollection(collectionName);
FindIterable<Document> findIterable = collection.find(query.getQuery());
if (fields == null) {
findIterable.projection(new MongodbFields().getDbObject());
} else {
findIterable.projection(fields.getDbObject());
}
if (sort != null) {
findIterable.sort(sort.getDbObject());
}
findIterable.limit(1);
MongoCursor<Document> cursor = findIterable.iterator();
try {
if (cursor.hasNext()) {
return cursor.next();
}
} finally {
cursor.close();
}
return null;
}
示例2: findAndConsumer
import com.mongodb.client.FindIterable; //導入方法依賴的package包/類
/**
* 查詢並逐條處理
*
* @param collectionName 集合名
* @param query 查詢條件
* @param fields 返回字段或者排除字段
* @param sort 排序方式
* @param consumer 記錄處理
* @return
*/
public void findAndConsumer(
String collectionName,
MongodbQuery query, MongodbFields fields,
MongodbSort sort, Consumer<Map<String, Object>> consumer) {
MongoCollection<Document> collection = sMongoDatabase.getCollection(collectionName);
FindIterable<Document> findIterable = collection.find(query == null ? new Document() : query.getQuery());
if (fields == null) {
findIterable.projection(new MongodbFields().getDbObject());
} else {
findIterable.projection(fields.getDbObject());
}
if (sort != null) {
findIterable.sort(sort.getDbObject());
}
MongoCursor<Document> cursor = findIterable.iterator();
try {
while (cursor.hasNext()) {
Map<String, Object> document = cursor.next();
consumer.accept(document);
}
} finally {
cursor.close();
}
}
示例3: findAll
import com.mongodb.client.FindIterable; //導入方法依賴的package包/類
/**
* 查詢
*
* @param clazz 類
* @param collectionName 集合名
* @param sort 排序
* @param <T>
* @return
*/
public <T> List<T> findAll(Class<T> clazz, String collectionName, MongodbSort sort) {
List<T> resultMapList = new ArrayList<T>();
MongoCollection<Document> collection = sMongoDatabase.getCollection(collectionName);
FindIterable<Document> findIterable = collection.find();
if(sort != null) {
findIterable.sort(sort.getDbObject());
}
MongoCursor<Document> cursor = findIterable.iterator();
try {
while (cursor.hasNext()) {
Document document = cursor.next();
T parseObject = JSON.parseObject(JSON.toJSONString(document), clazz);
resultMapList.add(parseObject);
}
} finally {
cursor.close();
}
return resultMapList;
}
示例4: query
import com.mongodb.client.FindIterable; //導入方法依賴的package包/類
private FindIterable<Document> query(final Bson filter, final Bson sort, final Bson projection, final int offset, final int count) {
if (offset < 0 || count < 0) {
throw new IllegalArgumentException("offset (" + offset + ") and count(" + count + ") can't be negative");
}
FindIterable<Document> findIterable = coll.find(filter);
if (projection != null) {
findIterable = findIterable.projection(projection);
}
if (sort != null) {
findIterable = findIterable.sort(sort);
}
if (offset > 0) {
findIterable = findIterable.skip(offset);
}
if (count < Integer.MAX_VALUE) {
findIterable = findIterable.limit(count);
}
return findIterable;
}
示例5: onTrigger
import com.mongodb.client.FindIterable; //導入方法依賴的package包/類
@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
FlowFile flowFile = session.get();
if (flowFile == null) {
return;
}
ComponentLog logger = this.getLogger();
// Evaluate expression language and create BSON Documents
Document query = (queryProperty.isSet()) ? Document.parse(queryProperty.evaluateAttributeExpressions(flowFile).getValue()) : null;
Document projection = (projectionProperty.isSet()) ? Document.parse(projectionProperty.evaluateAttributeExpressions(flowFile).getValue()) : null;
Document sort = (sortProperty.isSet()) ? Document.parse(sortProperty.evaluateAttributeExpressions(flowFile).getValue()) : null;
try {
FindIterable<Document> it = (query != null) ? collection.find(query) : collection.find();
// Apply projection if needed
if (projection != null) {
it.projection(projection);
}
// Apply sort if needed
if (sort != null) {
it.sort(sort);
}
// Apply limit if set
if (limit != null) {
it.limit(limit.intValue());
}
// Iterate and create flowfile for each result
final MongoCursor<Document> cursor = it.iterator();
try {
while (cursor.hasNext()) {
// Create new flowfile with all parent attributes
FlowFile ff = session.clone(flowFile);
ff = session.write(ff, new OutputStreamCallback() {
@Override
public void process(OutputStream outputStream) throws IOException {
IOUtils.write(cursor.next().toJson(), outputStream);
}
});
session.transfer(ff, REL_SUCCESS);
}
} finally {
cursor.close();
session.remove(flowFile);
}
} catch (Exception e) {
logger.error("Failed to execute query {} due to {}.", new Object[]{query, e}, e);
flowFile = session.putAttribute(flowFile, "mongo.exception", e.getMessage());
session.transfer(flowFile, REL_FAILURE);
}
}
示例6: find
import com.mongodb.client.FindIterable; //導入方法依賴的package包/類
/**
* 查詢
*
* @param collectionName 集合名
* @param query 查詢條件
* @param fields 返回字段或者排除字段
* @param sort 排序方式
* @param pageInfo 分頁
* @return
*/
public List<Map<String, Object>> find(
String collectionName,
MongodbQuery query, MongodbFields fields,
MongodbSort sort, MongodbPageInfo pageInfo) {
List<Map<String, Object>> resultMapList = new ArrayList<Map<String, Object>>();
MongoCollection<Document> collection = sMongoDatabase.getCollection(collectionName);
FindIterable<Document> findIterable = collection.find(query == null ? new Document() : query.getQuery());
if (fields == null) {
findIterable.projection(new MongodbFields().getDbObject());
} else {
findIterable.projection(fields.getDbObject());
}
if (sort != null) {
findIterable.sort(sort.getDbObject());
}
if (pageInfo != null) {
int startPos = pageInfo.getPageIndex() * pageInfo.getPageSize();
int rows = pageInfo.getPageSize();
if (startPos > 0) {
findIterable.skip(startPos - 1);
}
findIterable.limit(rows);
}
MongoCursor<Document> cursor = findIterable.iterator();
try {
while (cursor.hasNext()) {
Map<String, Object> document = cursor.next();
resultMapList.add(document);
}
} finally {
cursor.close();
}
return resultMapList;
}
示例7: fetchDataFromBackEnd
import com.mongodb.client.FindIterable; //導入方法依賴的package包/類
protected List<T> fetchDataFromBackEnd(Query<T, Bson> query) {
Bson filter = getFilter(query);
FindIterable<T> findIterable = mongoCollection.find();
if (filter != null) findIterable = findIterable.filter(filter);
findIterable = findIterable.skip(query.getOffset());
findIterable = findIterable.limit(query.getLimit());
findIterable = findIterable.sort(getSorts(query.getSortOrders()));
final List<T> data = new ArrayList<T>();
findIterable.iterator().forEachRemaining(data::add);
return data;
}
示例8: getDocuments
import com.mongodb.client.FindIterable; //導入方法依賴的package包/類
public List<Document> getDocuments(List<KeyValue> cond, RESOURCE_TYPE resType, String sortKey, boolean asc, int limit) {
ArrayList<Document> docList = new ArrayList<Document>();
Iterator<KeyValue> it = cond.iterator();
KeyValue kv = it.next();
BasicDBObject query = new BasicDBObject(kv.getKey(), kv.getValue());
while (it.hasNext()) {
kv = it.next();
query.append(kv.getKey(), kv.getValue());
}
BasicDBObject sort = null;
if (sortKey != null) {
sort = new BasicDBObject(sortKey, asc ? 1 : -1);
}
MongoCollection<Document> collection = context.getDatabaseManager()
.getCollection(collectionName);
MongoCursor<Document> cursor;
FindIterable<Document> find = collection.find(query);
if (sort != null) {
find = find.sort(sort);
}
if (limit >= 0) {
find = find.limit(limit);
}
cursor = find.iterator();
while (cursor.hasNext()) {
docList.add(cursor.next());
}
return docList;
}
示例9: read
import com.mongodb.client.FindIterable; //導入方法依賴的package包/類
@ExtDirectMethod(STORE_READ)
public ExtDirectStoreResult<User> read(ExtDirectStoreReadRequest request) {
List<Bson> andFilters = new ArrayList<>();
StringFilter filter = request.getFirstFilterForField("filter");
if (filter != null) {
List<Bson> orFilters = new ArrayList<>();
orFilters.add(Filters.regex(CUser.loginName, filter.getValue(), "i"));
orFilters.add(Filters.regex(CUser.lastName, filter.getValue(), "i"));
orFilters.add(Filters.regex(CUser.firstName, filter.getValue(), "i"));
orFilters.add(Filters.regex(CUser.email, filter.getValue(), "i"));
andFilters.add(Filters.or(orFilters));
}
andFilters.add(Filters.eq(CUser.deleted, false));
long total = this.mongoDb.getCollection(User.class)
.count(Filters.and(andFilters));
FindIterable<User> find = this.mongoDb.getCollection(User.class)
.find(Filters.and(andFilters));
find.sort(Sorts.orderBy(QueryUtil.getSorts(request)));
find.skip(request.getStart());
find.limit(request.getLimit());
return new ExtDirectStoreResult<>(total, QueryUtil.toList(find));
}
示例10: getCachedChronoVertices
import com.mongodb.client.FindIterable; //導入方法依賴的package包/類
public ArrayList<CachedChronoVertex> getCachedChronoVertices(BsonArray filters, String sortKey, Boolean isDesc,
Integer limit) {
ArrayList<CachedChronoVertex> vList = new ArrayList<CachedChronoVertex>();
// Merge All the queries with $and
CachedChronoGraph g = new CachedChronoGraph();
BsonDocument baseQuery = new BsonDocument();
FindIterable<BsonDocument> cursor;
if (filters.isEmpty() == false) {
baseQuery.put("$and", filters);
cursor = vertices.find(baseQuery);
} else {
cursor = vertices.find();
}
if (sortKey != null) {
if (isDesc == null)
cursor.sort(new BsonDocument(sortKey, new BsonInt32(-1)));
else if (isDesc == true) {
cursor.sort(new BsonDocument(sortKey, new BsonInt32(-1)));
} else
cursor.sort(new BsonDocument(sortKey, new BsonInt32(1)));
}
if (limit != null)
cursor.limit(limit);
MongoCursor<BsonDocument> iter = cursor.iterator();
while (iter.hasNext()) {
BsonDocument doc = iter.next();
String vid = doc.remove("_id").asString().getValue();
CachedChronoVertex v = g.getChronoVertex(vid);
v.setProperties(doc);
vList.add(v);
}
return vList;
}
示例11: load
import com.mongodb.client.FindIterable; //導入方法依賴的package包/類
/**
* load the data by the query.
*
* @param <T>
* the subclass of Bean
* @param collection
* the collection name
* @param query
* the query
* @param order
* the order
* @param b
* the Bean
* @param db
* the db
* @return the Bean
*/
public <T extends Bean> T load(String collection, String[] fields, Bson query, Bson order, T b, String db) {
TimeStamp t = TimeStamp.create();
try {
MongoCollection<Document> db1 = getCollection(db, collection);
if (db1 != null) {
FindIterable<Document> d = db1.find(query);
if (order != null) {
d.sort(order);
}
if (d != null) {
Document d1 = d.first();
if (log.isDebugEnabled())
log.debug("load - cost=" + t.pastms() + "ms, collection=" + collection + ", db=" + db
+ ", query=" + query + ", order=" + order + ", d=" + (d1 != null ? 1 : 0));
if (d1 != null) {
b.load(d1, fields);
return b;
}
// MongoCursor<Document> it = d.iterator();
// if (it.hasNext()) {
// b.load(it.next());
// return b;
// }
} else {
if (log.isDebugEnabled())
log.debug("load - cost=" + t.pastms() + "ms, collection=" + collection + ", query=" + query
+ ", order=" + order + ", result=" + null);
}
}
} catch (Exception e) {
if (log.isErrorEnabled())
log.error("query=" + query + ", order=" + order, e);
}
return null;
}
示例12: runNativeQuery
import com.mongodb.client.FindIterable; //導入方法依賴的package包/類
@Override
public RaptureQueryResult runNativeQuery(final String repoType, final List<String> queryParams) {
if (repoType.toUpperCase().equals(MONGODB)) {
MongoRetryWrapper<RaptureQueryResult> wrapper = new MongoRetryWrapper<RaptureQueryResult>() {
@Override
public FindIterable<Document> makeCursor() {
// Here we go, the queryParams are basically
// (1) the searchCriteria
Document queryObj = getQueryObjFromQueryParams(queryParams);
// Document fieldObj =
// getFieldObjFromQueryParams(queryParams);
MongoCollection<Document> collection = MongoDBFactory.getCollection(instanceName, tableName);
FindIterable<Document> find = collection.find(queryObj).batchSize(100);
if (queryParams.size() > 2) {
Map<String, Object> options = JacksonUtil.getMapFromJson(queryParams.get(2));
if (options.containsKey(SKIP)) {
find.skip((Integer) options.get(SKIP));
}
if (options.containsKey(LIMIT)) {
find.limit((Integer) options.get(LIMIT));
}
if (options.containsKey(SORT)) {
Map<String, Object> sortInfo = JacksonUtil.getMapFromJson(options.get(SORT).toString());
Document sortInfoObject = new Document();
sortInfoObject.putAll(sortInfo);
find.sort(sortInfoObject);
}
}
return find;
}
@Override
public RaptureQueryResult action(FindIterable<Document> iterable) {
RaptureQueryResult res = new RaptureQueryResult();
for (Document d : iterable) {
res.addRowContent(new JsonContent(d.toString()));
}
return res;
}
};
return wrapper.doAction();
} else {
throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, mongoMsgCatalog.getMessage("Mismatch", repoType));
}
}
示例13: createDoFindAll
import com.mongodb.client.FindIterable; //導入方法依賴的package包/類
private Function<Exchange, Object> createDoFindAll() {
return exchange1 -> {
Iterable<BasicDBObject> result;
MongoCollection<BasicDBObject> dbCol = calculateCollection(exchange1);
// do not use getMandatoryBody, because if the body is empty we want to retrieve all objects in the collection
BasicDBObject query = null;
// do not run around looking for a type converter unless there is a need for it
if (exchange1.getIn().getBody() != null) {
query = exchange1.getIn().getBody(BasicDBObject.class);
}
BasicDBObject fieldFilter = exchange1.getIn().getHeader(MongoDbConstants.FIELDS_FILTER, BasicDBObject.class);
// get the batch size and number to skip
Integer batchSize = exchange1.getIn().getHeader(MongoDbConstants.BATCH_SIZE, Integer.class);
Integer numToSkip = exchange1.getIn().getHeader(MongoDbConstants.NUM_TO_SKIP, Integer.class);
Integer limit = exchange1.getIn().getHeader(MongoDbConstants.LIMIT, Integer.class);
BasicDBObject sortBy = exchange1.getIn().getHeader(MongoDbConstants.SORT_BY, BasicDBObject.class);
FindIterable<BasicDBObject> ret;
if (query == null && fieldFilter == null) {
ret = dbCol.find(new BasicDBObject());
} else if (fieldFilter == null) {
ret = dbCol.find(query);
} else {
ret = dbCol.find(new BasicDBObject()).projection(fieldFilter);
}
if (sortBy != null) {
ret.sort(sortBy);
}
if (batchSize != null) {
ret.batchSize(batchSize);
}
if (numToSkip != null) {
ret.skip(numToSkip);
}
if (limit != null) {
ret.limit(limit);
}
if (!MongoDbOutputType.DBCursor.equals(endpoint.getOutputType())) {
try {
result = new ArrayList<>();
ret.iterator().forEachRemaining(((List<BasicDBObject>) result)::add);
exchange1.getOut().setHeader(MongoDbConstants.RESULT_PAGE_SIZE, ((List<BasicDBObject>) result).size());
} finally {
ret.iterator().close();
}
} else {
result = ret;
}
return result;
};
}
示例14: getData
import com.mongodb.client.FindIterable; //導入方法依賴的package包/類
@Override
public String getData(String filter, int max, String sort) throws ServiceException {
MongoDBHelper ds = new MongoDBHelper();
MongoDatabase db = ds.getConnection();
try {
MongoCollection<Document> c = db.getCollection(org.opengrid.constants.DB.DATA_COLLECTION_NAME);
BasicDBObject q = new BasicDBObject();
if (filter !=null && filter.length() > 0) {
BasicDBObject o = (BasicDBObject) JSON.parse(filter);
o.append("type", new BasicDBObject("$eq", "tweet"));
q = o;
} else
q = new BasicDBObject("type", new BasicDBObject("$eq", "tweet"));
FindIterable<Document> cur = c.find(q);
MongoCursor<Document> it = cur.iterator();
if (sort !=null && sort.length() > 0) {
BasicDBObject orderBy = (BasicDBObject) JSON.parse(sort);
cur.sort(orderBy);
}
//return geoJson object as part of our mock implementation
StringBuilder sb = new StringBuilder();
sb.append("{ \"type\" : \"FeatureCollection\", \"features\" : [");
int i=0;
while(it.hasNext()) {
if (i==max)
break;
Document doc = it.next();
if (i > 0)
sb.append(",");
sb.append(getFeature(doc));
i++;
//temp limit
//if (i==500)
// break;
}
sb.append("],");
sb.append(getMeta());
sb.append("}");
return sb.toString();
} catch (Exception ex) {
ex.printStackTrace();
//wrap and bubble up
throw ExceptionUtil.getException(Exceptions.ERR_DB, ex.getMessage());
} finally {
if (ds !=null) {
ds.closeConnection();
}
}
}
示例15: getData
import com.mongodb.client.FindIterable; //導入方法依賴的package包/類
@Override
public String getData(String filter, int max, String sort) throws ServiceException {
MongoDBHelper ds = new MongoDBHelper();
MongoDatabase db = ds.getConnection();
try {
MongoCollection<Document> c = db.getCollection(org.opengrid.constants.DB.DATA_COLLECTION_NAME);
BasicDBObject q = new BasicDBObject();
if (filter !=null && filter.length() > 0) {
BasicDBObject o = (BasicDBObject) JSON.parse(filter);
o.append("type", new BasicDBObject("$eq", "weather"));
q = o;
} else
q = new BasicDBObject("type", new BasicDBObject("$eq", "weather"));
FindIterable<Document> cur = c.find(q);
MongoCursor<Document> it = cur.iterator();
if (sort !=null && sort.length() > 0) {
BasicDBObject orderBy = (BasicDBObject) JSON.parse(sort);
cur.sort(orderBy);
}
//return geoJson object as part of our mock implementation
StringBuilder sb = new StringBuilder();
sb.append("{ \"type\" : \"FeatureCollection\", \"features\" : [");
int i=0;
while(it.hasNext()) {
if (i==max)
break;
Document doc = it.next();
if (i > 0)
sb.append(",");
sb.append(getFeature(doc));
i++;
//temp limit
//if (i==1000)
// break;
}
sb.append("],");
sb.append(getMeta());
sb.append("}");
return sb.toString();
} catch (Exception ex) {
ex.printStackTrace();
//wrap and bubble up
throw ExceptionUtil.getException(Exceptions.ERR_DB, ex.getMessage());
} finally {
if (ds !=null) {
ds.closeConnection();
}
}
}