Example usage for com.mongodb DBCollection find

List of usage examples for com.mongodb DBCollection find

Introduction

In this page you can find the example usage for com.mongodb DBCollection find.

Prototype

public DBCursor find(@Nullable final DBObject query, final DBCollectionFindOptions options) 

Source Link

Document

Select documents in collection and get a cursor to the selected documents.

Usage

From source file:com.impetus.client.mongodb.MongoDBClient.java

License:Apache License

/**
 * Gets the DB cursor instance.//from w w w .  ja  va  2 s . c  om
 * 
 * @param mongoQuery
 *            the mongo query
 * @param orderBy
 *            the order by
 * @param maxResult
 *            the max result
 * @param firstResult
 *            the first result
 * @param keys
 *            the keys
 * @param documentName
 *            the document name
 * @param isCountQuery
 *            the is count query
 * @return the DB cursor instance
 */
public Object getDBCursorInstance(BasicDBObject mongoQuery, BasicDBObject orderBy, int maxResult,
        int firstResult, BasicDBObject keys, String documentName, boolean isCountQuery) {
    DBCollection dbCollection = mongoDb.getCollection(documentName);
    DBCursor cursor = null;
    if (isCountQuery)
        return dbCollection.count(mongoQuery);
    else
        cursor = orderBy != null
                ? dbCollection.find(mongoQuery, keys).sort(orderBy).limit(maxResult).skip(firstResult)
                : dbCollection.find(mongoQuery, keys).limit(maxResult).skip(firstResult);
    return cursor;
}

From source file:com.intuit.tweetstest.TweetsController.java

protected JSONArray retrieveTweetsFromDB(DB db, List<String> followingList, int count) throws ParseException {
    JSONArray tweetsArray = new JSONArray();
    DBCollection tweetsCollection = db.getCollection("tweetscollection");
    DBObject tweetsQuery = new BasicDBObject("user", new BasicDBObject("$in", followingList));
    DBObject excludeId = new BasicDBObject("_id", 0);
    DBCursor cursor = tweetsCollection.find(tweetsQuery, excludeId).sort(new BasicDBObject("tweetedOn", -1))
            .limit(count);//w w w.ja v a2  s  .c  om
    for (DBObject tweet : cursor) {
        JSONObject tweetJson = (JSONObject) new JSONParser().parse(tweet.toString());
        tweetsArray.add(tweetJson);
    }
    return tweetsArray;
}

From source file:com.jaspersoft.mongodb.query.MongoDbQueryWrapper.java

License:Open Source License

private void createIterator() throws JRException {
    if (!queryObject.containsField(COLLECTION_NAME_KEY)) {
        throw new JRException("\"" + COLLECTION_NAME_KEY + "\" must be part of the query object");
    }/*from w  ww.  j av a 2  s.  c om*/
    DBObject findQueryObject = (DBObject) queryObject.get(FIND_QUERY_KEY);
    if (findQueryObject == null) {
        findQueryObject = new BasicDBObject();
    }
    if (queryObject.containsField(FIND_QUERY_REGEXP_KEY)) {
        DBObject regExpObject = (DBObject) queryObject.get(FIND_QUERY_REGEXP_KEY);
        String value, flags;
        int index;
        for (String key : regExpObject.keySet()) {
            value = (String) regExpObject.get(key);
            if (value.startsWith("/")) {
                value = value.substring(1, value.length());
            } else {
                throw new JRException("Regular expressions must start with: /");
            }
            if (!value.contains("/")) {
                throw new JRException("No ending symbol found: /");
            }
            index = value.lastIndexOf("/");
            flags = null;
            if (index == value.length() - 1) {
                value = value.substring(0, index);
            } else {
                flags = value.substring(index + 1, value.length());
                value = value.substring(0, index);
            }
            findQueryObject.put(key, Pattern.compile((flags != null ? "(?" + flags + ")" : "") + value));
        }
    }

    DBCollection collection = connection.getMongoDatabase()
            .getCollectionFromString((String) queryObject.removeField(COLLECTION_NAME_KEY));
    if (queryObject.containsField(MAP_REDUCE_KEY)) {
        Object value = queryObject.removeField(MAP_REDUCE_KEY);
        if (!(value instanceof DBObject)) {
            logger.error("MapReduce value must be a valid JSON object");
        } else {
            DBObject mapReduceObject = (DBObject) value;
            String map = validateProperty(mapReduceObject, MAP_KEY);
            String reduce = validateProperty(mapReduceObject, REDUCE_KEY);
            Object outObject = mapReduceObject.get(OUT_KEY);
            if (outObject == null) {
                throw new JRException("\"out\" cannot be null");
            }
            String collectionName = null;
            Object outDb = null;
            OutputType outputType = null;
            boolean hasOutputType = false;
            if (logger.isDebugEnabled()) {
                logger.debug("Out object: " + outObject + ". Type: " + outObject.getClass().getName());
            }
            if (outObject instanceof String) {
                collectionName = String.valueOf(outObject);
            } else if (outObject instanceof DBObject) {
                DBObject outDbObject = (DBObject) outObject;
                outDb = outDbObject.removeField(OUT_DB_KEY);
                Iterator<String> keysIterator = outDbObject.keySet().iterator();
                String type = null;
                if (keysIterator.hasNext()) {
                    type = keysIterator.next();
                    collectionName = String.valueOf(outDbObject.get(type));
                } else {
                    throw new JRException("\"out\" object cannot be empty");
                }
                type = type.toUpperCase();
                outputType = OutputType.valueOf(type);
                if (outputType == null) {
                    throw new JRException("Unknow output type: " + type);
                }
                hasOutputType = true;
                if (logger.isDebugEnabled()) {
                    logger.debug("outobject: " + outDbObject);
                    logger.debug("collectionName: " + collectionName);
                    logger.debug("outputType: " + outputType);
                }
            } else {
                throw new JRException("Unsupported type for \"out\": " + outObject.getClass().getName());
            }
            MapReduceCommand mapReduceCommand = new MapReduceCommand(collection, map, reduce, collectionName,
                    hasOutputType ? outputType : OutputType.REPLACE, null);
            if (outDb != null) {
                mapReduceCommand.setOutputDB(String.valueOf(outDb));
            }
            Object finalizeObject = mapReduceObject.removeField(FINALIZE_KEY);
            if (finalizeObject != null) {
                mapReduceCommand.setFinalize(String.valueOf(finalizeObject));
            }
            MapReduceOutput mapReduceOutput = collection.mapReduce(mapReduceCommand);
            DBCollection mapReduceCollection = mapReduceOutput.getOutputCollection();
            if (mapReduceCollection != null) {
                collection = mapReduceCollection;
            }
        }
    }

    iterator = collection.find(findQueryObject, (DBObject) queryObject.get(FIND_FIELDS_KEY));
    if (queryObject.containsField(SORT_KEY)) {
        iterator = iterator.sort((DBObject) queryObject.get(SORT_KEY));
    }
    if (queryObject.containsField(LIMIT_KEY)) {
        Integer value = processInteger(queryObject.get(LIMIT_KEY));
        if (value != null) {
            iterator = iterator.limit(value.intValue());
        }
    }
}

From source file:com.joyfulmongo.db.javadriver.JFDBQuery.java

License:Apache License

public List<JFDBObject> find() {
    long start = System.currentTimeMillis();
    DBCollection collection = getDBCollection(collectionName);

    List<JFDBObject> result = new ArrayList<JFDBObject>(0);
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.log(Level.FINE,/*from  ww  w.  jav  a  2s  .  c o m*/
                "Find collection=" + collection + "\n" + " constraints " + constraints + "\n" + " projections="
                        + projections + "\n" + " limit=" + limit + "\n" + " skip=" + skip + "\n" + " sortby="
                        + sortBy + "\n");
    }

    DBCursor cursor = collection.find(constraints, projections).limit(limit).skip(skip).sort(sortBy);
    while (cursor.hasNext()) {
        DBObject obj = cursor.next();
        result.add(new JFDBObject(collectionName, obj));
    }

    MonitorManager.getInstance().logQuery(collectionName, JFDBUtil.toJSONObject(constraints),
            JFDBUtil.toJSONObject(sortBy), System.currentTimeMillis() - start);

    return result;
}

From source file:com.joyfulmongo.db.javadriver.MongoQuery.java

License:Apache License

public List<MongoObject> find() {
    long start = System.currentTimeMillis();
    DBCollection collection = getDBCollection(collectionName);

    List<MongoObject> result = new ArrayList<MongoObject>(limit);
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.log(Level.FINE,/*from w  ww .  j  av a  2s . com*/
                "Find collection=" + collection + "\n" + " constraints " + constraints + "\n" + " projections="
                        + projections + "\n" + " limit=" + limit + "\n" + " skip=" + skip + "\n" + " sortby="
                        + sortBy + "\n");
    }

    DBCursor cursor = collection.find(constraints, projections).sort(sortBy).skip(skip).limit(limit + skip);

    while (cursor.hasNext()) {
        result.add(new MongoObject(collectionName, cursor.next()));
    }

    MonitorManager.getInstance().logQuery(collectionName, MongoDBUtil.toJSONObject(constraints),
            MongoDBUtil.toJSONObject(sortBy), System.currentTimeMillis() - start);

    return result;
}

From source file:com.mobileman.moments.core.services.notification.impl.gcn.question.GCNQuestionNotifications.java

License:Apache License

@SuppressWarnings("unchecked")
@ServiceActivator(inputChannel = MomentsESBConstants.QUESTION_CREATED_CHANNEL)
public void questionCreated(final Question question) {

    final String location = "";
    final String alert = this.messageSource.getMessage("push_notification.new_question_in_interest.alert",
            new Object[] { location }, LocalizationUtils.DEFAULT_LOCALE);
    final String title = this.messageSource.getMessage("push_notification.new_question_in_interest.title",
            new Object[] { "name" }, null, LocalizationUtils.DEFAULT_LOCALE);
    final User loggedUser = SecurityUtils.getLoggedUser();

    mongoTemplate.execute(User.class, new CollectionCallback<Void>() {

        @Override/*from w  w w. j  a v a  2 s .c  o  m*/
        public Void doInCollection(DBCollection collection) throws MongoException, DataAccessException {
            Query query = Query.query(Criteria.where("interests._id").is(new ObjectId("id")).and("_id")
                    .ne(new ObjectId(loggedUser.getId())));
            query.fields().include("_id");
            query.fields().include("interests");

            DBCursor cursor = collection.find(query.getQueryObject(), query.getFieldsObject());
            for (DBObject dbObject : cursor) {
                // UserSettings = settings = dbObject.get
                ObjectId userId = (ObjectId) dbObject.get("_id");

                List<DBObject> interests = (List<DBObject>) dbObject.get("interests");

                for (DBObject interest : interests) {
                    if (interest.get("_id").toString().equals("id")) {
                        if (interest.containsField("following_questions")
                                && Boolean.TRUE.equals(interest.get("following_questions"))) {
                            //notificationService.questionByInterestCreated(question, userId.toString(), alert, title);
                        }
                    }
                }

                // if (settings.getFollowesQuestionsNotification().isEnabled()) 
                // UserPushNotificationEvent event = new UserPushNotificationEvent(userId.toString(), title, alert);
                // momentsGateway.postPushNotificationEvent(event);

            }

            return null;
        }

    });
}

From source file:com.mobileman.moments.core.services.user.impl.UserStatsServiceImpl.java

License:Apache License

@Async
@Scheduled(cron = "${user_stats_update_job.cron.expression}")
public void computeUserStats() {

    mongoTemplate.execute(User.class, new CollectionCallback<Void>() {

        @Override//from   w w  w. j  a v  a2 s  .  com
        public Void doInCollection(DBCollection collection) throws MongoException, DataAccessException {

            DBCursor cursor = collection.find(new BasicDBObject(), new BasicDBObject("_id", 1));
            for (DBObject dbObject : cursor) {
                ObjectId _id = (ObjectId) dbObject.get("_id");
                computeUserStats(_id);
            }

            return null;
        }
    });
}

From source file:com.nec.strudel.tkvs.store.mongodb.MongodbTransaction.java

License:Apache License

static long tryGetVnum(DBCollection coll, String docName) {
    DBCursor cur = coll.find(new BasicDBObject(MongoDbServer.DOCNAME, docName),
            new BasicDBObject(MongoDbServer.VERSIONFIELD, 1)).limit(1);
    DBObject versionObj = null;//  w w  w .  j a v a  2s  .c om
    if (cur.hasNext()) {
        versionObj = cur.next();
    }
    if (versionObj != null) {
        return Long.parseLong(versionObj.get(MongoDbServer.VERSIONFIELD).toString());
    } else {
        return 0L;
    }

}

From source file:com.querydsl.mongodb.AbstractMongodbQuery.java

License:Apache License

protected DBCursor createCursor(DBCollection collection, @Nullable Predicate where, Expression<?> projection,
        QueryModifiers modifiers, List<OrderSpecifier<?>> orderBy) {
    DBCursor cursor = collection.find(createQuery(where), createProjection(projection));
    Integer limit = modifiers.getLimitAsInteger();
    Integer offset = modifiers.getOffsetAsInteger();
    if (limit != null) {
        cursor.limit(limit);/*from  w  ww .  j a  v  a  2s .  c  o m*/
    }
    if (offset != null) {
        cursor.skip(offset);
    }
    if (orderBy.size() > 0) {
        cursor.sort(serializer.toSort(orderBy));
    }
    if (readPreference != null) {
        cursor.setReadPreference(readPreference);
    }
    return cursor;
}

From source file:com.querydsl.mongodb.MongodbQuery.java

License:Apache License

protected DBCursor createCursor(DBCollection collection, @Nullable Predicate where, Expression<?> projection,
        QueryModifiers modifiers, List<OrderSpecifier<?>> orderBy) {
    DBCursor cursor = collection.find(createQuery(where), createProjection(projection));
    Integer limit = modifiers.getLimitAsInteger();
    Integer offset = modifiers.getOffsetAsInteger();
    if (limit != null) {
        cursor.limit(limit.intValue());//from  w  w w.  j a  v a 2s .  c  o  m
    }
    if (offset != null) {
        cursor.skip(offset.intValue());
    }
    if (orderBy.size() > 0) {
        cursor.sort(serializer.toSort(orderBy));
    }
    if (readPreference != null) {
        cursor.setReadPreference(readPreference);
    }
    return cursor;
}