List of usage examples for com.mongodb DBCursor sort
public DBCursor sort(final DBObject orderBy)
From source file:org.mule.module.mongo.tools.MongoDump.java
License:Open Source License
private void initOplog(final String database) throws IOException { if (oplog) {// w w w .j a v a2s. co m oplogCollection = new OplogCollection(dbs.get(BackupConstants.ADMIN_DB), dbs.get(BackupConstants.LOCAL_DB)).getOplogCollection(); // Filter for oplogs for the given database final DBObject query = new BasicDBObject(BackupConstants.NAMESPACE_FIELD, BackupUtils.getNamespacePattern(database)); final DBCursor oplogCursor = oplogCollection.find(query); oplogCursor.sort(new BasicDBObject("$natural", -1)); if (oplogCursor.hasNext()) { oplogStart = ((BSONTimestamp) oplogCursor.next().get("ts")); } } }
From source file:org.mule.module.mongo.tools.MongoDumpCollection.java
License:Open Source License
public Void call() throws Exception { final DBCursor cursor = query != null ? collection.find(query) : collection.find(); cursor.sort(new BasicDBObject("_id", 1)); for (final Integer option : options) { cursor.addOption(option);/*from w ww . j av a2s . c om*/ } while (cursor.hasNext()) { final BasicDBObject dbObject = (BasicDBObject) cursor.next(); dumpWriter.writeObject(name != null ? name : collection.getName(), dbObject); } return null; }
From source file:org.netbeans.modules.mongodb.util.Exporter.java
License:Open Source License
private void export(Writer writer) { final PrintWriter output = new PrintWriter(writer); final DBCollection collection = db.getCollection(properties.getCollection()); final DBCursor cursor = collection.find(properties.getCriteria(), properties.getProjection()); if (properties.getSort() != null) { cursor.sort(properties.getSort()); }// w ww . j a v a2 s .c om if (properties.isJsonArray()) { output.print("["); } boolean first = true; for (DBObject document : cursor) { if (Thread.interrupted()) { return; } if (first) { first = false; } else if (properties.isJsonArray()) { output.print(","); } final String json = JSON.serialize(document); output.print(json); if (properties.isJsonArray() == false) { output.println(); } output.flush(); } if (properties.isJsonArray()) { output.println("]"); } output.flush(); }
From source file:org.s1.mongodb.MongoDBQueryHelper.java
License:Apache License
/** * * @param c//from w ww .ja v a 2s.c o m * @param search * @param sort * @param fields * @param skip * @param max * @return */ public static List<Map<String, Object>> list(CollectionId c, Map<String, Object> search, Map<String, Object> sort, Map<String, Object> fields, int skip, int max) { List<Map<String, Object>> res = Objects.newArrayList(); DBCollection coll = MongoDBConnectionHelper.getCollection(c); if (search == null) search = Objects.newHashMap(); DBCursor cur = coll.find(MongoDBFormat.fromMap(search), MongoDBFormat.fromMap(fields)); if (max > 0) cur.limit(max); if (skip >= 0) cur.skip(skip); if (sort != null) { cur = cur.sort(MongoDBFormat.fromMap(sort)); } while (cur.hasNext()) { DBObject obj = cur.next(); Map<String, Object> m = MongoDBFormat.toMap(obj); res.add(m); } if (LOG.isDebugEnabled()) LOG.debug("MongoDB list result (" + c + ", search:" + search + ", sort:" + sort + ", fields:" + fields + ", max:" + max + ", skip:" + skip + "\n\t> " + res); return res; }
From source file:org.springframework.data.document.mongodb.MongoTemplate.java
License:Apache License
public <T> List<T> find(String collectionName, final Query query, Class<T> targetClass) { CursorPreparer cursorPreparer = null; if (query.getSkip() > 0 || query.getLimit() > 0 || query.getSortObject() != null) { cursorPreparer = new CursorPreparer() { public DBCursor prepare(DBCursor cursor) { DBCursor cursorToUse = cursor; try { if (query.getSkip() > 0) { cursorToUse = cursorToUse.skip(query.getSkip()); }//from w ww .j ava 2 s . com if (query.getLimit() > 0) { cursorToUse = cursorToUse.limit(query.getLimit()); } if (query.getSortObject() != null) { cursorToUse = cursorToUse.sort(query.getSortObject()); } } catch (RuntimeException e) { throw potentiallyConvertRuntimeException(e); } return cursorToUse; } }; } return doFind(collectionName, query.getQueryObject(), query.getFieldsObject(), targetClass, cursorPreparer); }
From source file:org.springframework.datastore.mapping.mongo.query.MongoQuery.java
License:Apache License
@Override protected List executeQuery(final PersistentEntity entity, final Junction criteria) { final MongoTemplate template = mongoSession.getMongoTemplate(entity); return template.execute(new DbCallback<List>() { @Override//from w ww. j av a2 s . c o m public List doInDB(DB db) throws MongoException, DataAccessException { final DBCollection collection = db.getCollection(mongoEntityPersister.getCollectionName(entity)); if (uniqueResult) { final DBObject dbObject; if (criteria.isEmpty()) { if (entity.isRoot()) { dbObject = collection.findOne(); } else { DBObject query = new BasicDBObject(MongoEntityPersister.MONGO_CLASS_FIELD, entity.getDiscriminator()); dbObject = collection.findOne(query); } } else { DBObject query = getMongoQuery(); dbObject = collection.findOne(query); } final Object object = createObjectFromDBObject(dbObject); return wrapObjectResultInList(object); } else { DBCursor cursor; DBObject query = createQueryObject(entity); final List<Projection> projectionList = projections().getProjectionList(); if (projectionList.isEmpty()) { cursor = executeQuery(entity, criteria, collection, query); return new MongoResultList(cursor, mongoEntityPersister); } else { List projectedResults = new ArrayList(); for (Projection projection : projectionList) { if (projection instanceof CountProjection) { // For some reason the below doesn't return the expected result whilst executing the query and returning the cursor does //projectedResults.add(collection.getCount(query)); cursor = executeQuery(entity, criteria, collection, query); projectedResults.add(cursor.size()); } else if (projection instanceof MinProjection) { cursor = executeQuery(entity, criteria, collection, query); MinProjection mp = (MinProjection) projection; MongoResultList results = new MongoResultList(cursor, mongoEntityPersister); projectedResults.add( manualProjections.min((Collection) results.clone(), mp.getPropertyName())); } else if (projection instanceof MaxProjection) { cursor = executeQuery(entity, criteria, collection, query); MaxProjection mp = (MaxProjection) projection; MongoResultList results = new MongoResultList(cursor, mongoEntityPersister); projectedResults.add( manualProjections.max((Collection) results.clone(), mp.getPropertyName())); } else if ((projection instanceof PropertyProjection) || (projection instanceof IdProjection)) { final PersistentProperty persistentProperty; final String propertyName; if (projection instanceof IdProjection) { persistentProperty = entity.getIdentity(); propertyName = MongoEntityPersister.MONGO_ID_FIELD; } else { PropertyProjection pp = (PropertyProjection) projection; persistentProperty = entity.getPropertyByName(pp.getPropertyName()); propertyName = pp.getPropertyName(); } if (persistentProperty != null) { populateMongoQuery(entity, query, criteria); List propertyResults = collection.distinct(propertyName, query); if (persistentProperty instanceof ToOne) { Association a = (Association) persistentProperty; propertyResults = session.retrieveAll( a.getAssociatedEntity().getJavaClass(), propertyResults); } if (projectedResults.size() == 0 && projectionList.size() == 1) { return propertyResults; } else { projectedResults.add(propertyResults); } } else { throw new InvalidDataAccessResourceUsageException( "Cannot use [" + projection.getClass().getSimpleName() + "] projection on non-existent property: " + propertyName); } } } return projectedResults; } } } protected DBCursor executeQuery(final PersistentEntity entity, final Junction criteria, final DBCollection collection, DBObject query) { final DBCursor cursor; if (criteria.isEmpty()) { cursor = executeQueryAndApplyPagination(collection, query); } else { populateMongoQuery(entity, query, criteria); cursor = executeQueryAndApplyPagination(collection, query); } return cursor; } protected DBCursor executeQueryAndApplyPagination(final DBCollection collection, DBObject query) { final DBCursor cursor; cursor = collection.find(query); if (offset > 0) { cursor.skip(offset); } if (max > -1) { cursor.limit(max); } for (Order order : orderBy) { DBObject orderObject = new BasicDBObject(); orderObject.put(order.getProperty(), order.getDirection() == Order.Direction.DESC ? -1 : 1); cursor.sort(orderObject); } return cursor; } }); }
From source file:org.tylproject.vaadin.addon.MongoContainer.java
License:Apache License
/** * @return a cursor with the given optional params */// ww w .j av a 2s.c om protected DBCursor cursor(DBObject additionalCriteria) { final Query q = this.query; DBObject criteriaObject = q.getQueryObject(); if (additionalCriteria != null) { criteriaObject.putAll(additionalCriteria); } DBObject projectionObject = new BasicDBObject(ID, true); String collectionName = mongoOps.getCollectionName(beanClass); DBCollection dbCollection = mongoOps.getCollection(collectionName); // TODO: keep cursor around to possibly reuse DBCursor cursor = dbCollection.find(criteriaObject, projectionObject); if (this.baseSort != null || this.sort != null) { DBObject sortObject = q.getSortObject(); cursor.sort(sortObject); } return cursor; }
From source file:org.vertx.java.busmods.persistor.MongoPersistor.java
License:Apache License
private void doFind(Message<JsonObject> message) { String collection = getMandatoryString("collection", message); if (collection == null) { return;// w w w . j ava2 s.c o m } Integer limit = (Integer) message.body.getNumber("limit"); if (limit == null) { limit = -1; } Integer batchSize = (Integer) message.body.getNumber("batch_size"); if (batchSize == null) { batchSize = 100; } JsonObject matcher = getMandatoryObject("matcher", message); if (matcher == null) { return; } JsonObject sort = message.body.getObject("sort"); DBCollection coll = db.getCollection(collection); DBCursor cursor = coll.find(jsonToDBObject(matcher)); if (limit != -1) { cursor.limit(limit); } if (sort != null) { cursor.sort(jsonToDBObject(sort)); } sendBatch(message, cursor, batchSize); }
From source file:org.vertx.mods.MongoPersistor.java
License:Apache License
private void doFind(Message<JsonObject> message) { String collection = getMandatoryString("collection", message); if (collection == null) { return;//w w w . jav a 2 s . c om } Integer limit = (Integer) message.body.getNumber("limit"); if (limit == null) { limit = -1; } Integer skip = (Integer) message.body.getNumber("skip"); if (skip == null) { skip = -1; } Integer batchSize = (Integer) message.body.getNumber("batch_size"); if (batchSize == null) { batchSize = 100; } JsonObject matcher = getMandatoryObject("matcher", message); if (matcher == null) { return; } JsonObject keys = message.body.getObject("keys"); Object sort = message.body.getField("sort"); DBCollection coll = db.getCollection(collection); DBCursor cursor = (keys == null) ? coll.find(jsonToDBObject(matcher)) : coll.find(jsonToDBObject(matcher), jsonToDBObject(keys)); if (skip != -1) { cursor.skip(skip); } if (limit != -1) { cursor.limit(limit); } if (sort != null) { cursor.sort(sortObjectToDBObject(sort)); } sendBatch(message, cursor, batchSize); }
From source file:recomendacao.Recomendacao.java
/** * Filmes para o usurio//from www . j a v a 2 s .co m */ public void recomendar() { long startTime = System.currentTimeMillis(); double soma = 0; //Recuperar todos os usurios DBCursor usersCursor = usersCollection.find(); //Para cada usuro while (usersCursor.hasNext()) { long startTimeUser = System.currentTimeMillis(); BasicDBObject user = (BasicDBObject) usersCursor.next(); //Ver qual o gnero que ele mais assiste (baseado nos rates) //e recuperar todos os filmes assistidos pelo user DBCursor ratesCursor = ratesCollection.find(new BasicDBObject("userID", user.get("_id"))); Map<String, Integer> categoriasCount = new HashMap<>(); BasicDBList moviesAssistidos = new BasicDBList(); while (ratesCursor.hasNext()) { BasicDBObject rate = (BasicDBObject) ratesCursor.next(); //Recuperar o filme Integer movieID = rate.getInt("movieID"); BasicDBObject movie = (BasicDBObject) moviesCollection.findOne(new BasicDBObject("_id", movieID)); BasicDBList categories = (BasicDBList) movie.get("categories"); moviesAssistidos.add(movieID); try { //Guardar a contagem for (Object categoryObject : categories) { String category = (String) categoryObject; int count = 0; if (categoriasCount.containsKey(category)) { count = categoriasCount.get(category); } count++; categoriasCount.put(category, count); } } catch (NullPointerException ex) { System.out.println(movie.get("name") + " no tem categoria..."); } // System.out.println("movie: " + movie); // break; } //Selecionar a melhor categoria String melhorCategoria = null; int maior = -1; for (String category : categoriasCount.keySet()) { int count = categoriasCount.get(category); if (count > maior) { maior = count; melhorCategoria = category; } } BasicDBObject categoryObject = (BasicDBObject) categoriesCollection .findOne(new BasicDBObject("name", melhorCategoria)); BasicDBList todosMoviesDaCategoria = (BasicDBList) categoryObject.get("movies"); // System.out.println("moviesAssistidos: " + moviesAssistidos.size()); // System.out.println("todosMoviesDaCategoria: " + todosMoviesDaCategoria.size()); //Selecionar os filmes da categoria que o user no assistiu todosMoviesDaCategoria.removeAll(moviesAssistidos); // System.out.println("todosMoviesDaCategoria: " + todosMoviesDaCategoria.size()); BasicDBObject selectObject = new BasicDBObject(); selectObject.put("movieID", new BasicDBObject("$in", todosMoviesDaCategoria)); BasicDBObject sortObject = new BasicDBObject(); sortObject.put("rating", -1); sortObject.put("timestamp", -1); ratesCursor = ratesCollection.find(selectObject); ratesCursor.sort(sortObject); ratesCursor.limit(5); BasicDBList moviesRecomendados = new BasicDBList(); while (ratesCursor.hasNext()) { BasicDBObject rate = (BasicDBObject) ratesCursor.next(); Integer movieID = rate.getInt("movieID"); DBObject movie = moviesCollection.findOne(new BasicDBObject("_id", movieID)); moviesRecomendados.add(movie); } // System.out.println("Recomendao para " + user.getInt("_id") + ":"); // for (Object movie : moviesRecomendados) { // System.out.println("\t" + movie); // } // System.out.println(); long finishTimeUser = System.currentTimeMillis(); System.out.print("Tempo de execuo para recomendar o user " + user.getInt("_id") + ": "); System.out.println(((double) (finishTimeUser - startTimeUser)) / 1000.0 + " segundos."); soma += ((double) (finishTimeUser - startTimeUser)) / 1000.0; // break; } System.out.println(); System.out.println("Mdia de tempo de execuo para cada usurio: " + soma / 943.0 + " segundos."); System.out.println(); long finishTime = System.currentTimeMillis(); System.out.print("Tempo de execuo do algortmo: "); System.out.println(((double) (finishTime - startTime)) / 1000.0 + " segundos."); }