Example usage for com.mongodb DBCollection findOne

List of usage examples for com.mongodb DBCollection findOne

Introduction

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

Prototype

@Nullable
public DBObject findOne() 

Source Link

Document

Get a single document from collection.

Usage

From source file:org.pentaho.mongo.wrapper.NoAuthMongoClientWrapper.java

License:Open Source License

/**
 * Return a list of custom "lastErrorModes" (if any) defined in the replica set configuration object on the server.
 * These can be used as the "w" setting for the write concern in addition to the standard "w" values of <number> or
 * "majority"./*from ww w. j a va  2  s.c o  m*/
 *
 * @return a list of the names of any custom "lastErrorModes"
 * @throws MongoDbException if a problem occurs
 */
public List<String> getLastErrorModes() throws MongoDbException {
    List<String> customLastErrorModes = new ArrayList<String>();

    DB local = getDb(LOCAL_DB);
    if (local != null) {
        try {
            DBCollection replset = local.getCollection(REPL_SET_COLLECTION);
            if (replset != null) {
                DBObject config = replset.findOne();

                extractLastErrorModes(config, customLastErrorModes);
            }
        } catch (Exception e) {
            throw new MongoDbException(e);
        }
    }

    return customLastErrorModes;
}

From source file:org.pentaho.mongo.wrapper.NoAuthMongoClientWrapper.java

License:Open Source License

private BasicDBList getRepSetMemberRecords() throws MongoDbException {
    BasicDBList setMembers = null;//  www  .j  av  a  2  s.co m
    try {
        DB local = getDb(LOCAL_DB);
        if (local != null) {

            DBCollection replset = local.getCollection(REPL_SET_COLLECTION);
            if (replset != null) {
                DBObject config = replset.findOne();

                if (config != null) {
                    Object members = config.get(REPL_SET_MEMBERS);

                    if (members instanceof BasicDBList) {
                        if (((BasicDBList) members).size() == 0) {
                            // log that there are no replica set members defined
                            logInfo(BaseMessages.getString(PKG,
                                    "MongoNoAuthWrapper.Message.Warning.NoReplicaSetMembersDefined")); //$NON-NLS-1$
                        } else {
                            setMembers = (BasicDBList) members;
                        }

                    } else {
                        // log that there are no replica set members defined
                        logInfo(BaseMessages.getString(PKG,
                                "MongoNoAuthWrapper.Message.Warning.NoReplicaSetMembersDefined")); //$NON-NLS-1$
                    }
                } else {
                    // log that there are no replica set members defined
                    logInfo(BaseMessages.getString(PKG,
                            "MongoNoAuthWrapper.Message.Warning.NoReplicaSetMembersDefined")); //$NON-NLS-1$
                }
            } else {
                // log that the replica set collection is not available
                logInfo(BaseMessages.getString(PKG,
                        "MongoNoAuthWrapper.Message.Warning.ReplicaSetCollectionUnavailable")); //$NON-NLS-1$
            }
        } else {
            // log that the local database is not available!!
            logInfo(BaseMessages.getString(PKG, "MongoNoAuthWrapper.Message.Warning.LocalDBNotAvailable")); //$NON-NLS-1$
        }
    } catch (Exception ex) {
        throw new MongoDbException(ex);
    } finally {
        if (getMongo() != null) {
            getMongo().close();
        }
    }

    return setMembers;
}

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// www  .ja v  a  2s  .  c om
        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.teiid.translator.mongodb.MongoDBMetadataProcessor.java

License:Open Source License

@Override
public void process(MetadataFactory metadataFactory, MongoDBConnection connection) throws TranslatorException {
    DB db = connection.getDatabase();//from  w  w w . j  a v a  2s.c o m
    for (String tableName : db.getCollectionNames()) {

        DBCollection rows = db.getCollection(tableName);
        BasicDBObject row = (BasicDBObject) rows.findOne();
        Table table = addTable(metadataFactory, tableName, row);

        // top level documents can not be seen as merged
        table.setProperty(TOP_LEVEL_DOC, String.valueOf(Boolean.TRUE));
    }

    for (Table table : metadataFactory.getSchema().getTables().values()) {
        String merge = table.getProperty(MERGE, false);
        if (merge != null) {
            addForeignKey(metadataFactory, table, metadataFactory.getSchema().getTable(merge));
        }
    }

    for (Table table : metadataFactory.getSchema().getTables().values()) {
        String top = table.getProperty(TOP_LEVEL_DOC, false);
        String merge = table.getProperty(MERGE, false);
        if (top != null) {
            table.setProperty(TOP_LEVEL_DOC, null);
            if (merge != null) {
                table.setProperty(MERGE, null);
                table.setProperty(EMBEDDABLE, "true"); //$NON-NLS-1$
            }
        }
    }
}

From source file:org.vertx.java.busmods.persistor.MongoPersistor.java

License:Apache License

private void doFindOne(Message<JsonObject> message) {
    String collection = getMandatoryString("collection", message);
    if (collection == null) {
        return;/*from w w  w .  j  a va  2 s .c  om*/
    }
    JsonObject matcher = message.body.getObject("matcher");
    DBCollection coll = db.getCollection(collection);
    DBObject res;
    if (matcher == null) {
        res = coll.findOne();
    } else {
        res = coll.findOne(jsonToDBObject(matcher));
    }
    JsonObject reply = new JsonObject();
    if (res != null) {
        String s = res.toString();
        JsonObject m = new JsonObject(s);
        reply.putObject("result", m);
    }
    sendOK(message, reply);
}

From source file:parlare.application.server.model.Database.java

private String doClientMongo() {

    String print = "";

    System.out.println("User:" + user + " Source:" + source + " Password:" + password);

    try {/*ww w  .  j av a 2 s .  co  m*/

        // connect to the local database server
        MongoClient mongoClient = new MongoClient(new ServerAddress(server),
                Arrays.asList(MongoCredential.createMongoCRCredential(user, source, password.toCharArray())),
                new MongoClientOptions.Builder().build());

        // get handle to "mydb"
        DB db = mongoClient.getDB("html5apps");

        // Authenticate - optional
        // boolean auth = db.authenticate("foo", "bar");

        // get a list of the collections in this database and print them out
        Set<String> collectionNames = db.getCollectionNames();
        for (String s : collectionNames) {

            System.out.println(s);
        }

        // get a collection object to work with
        DBCollection testCollection = db.getCollection("testCollection");

        // drop all the data in it
        testCollection.drop();

        // make a document and insert it
        BasicDBObject doc = new BasicDBObject("name", "MongoDB").append("type", "database").append("count", 1)
                .append("info", new BasicDBObject("x", 203).append("y", 102));

        testCollection.insert(doc);

        // get it (since it's the only one in there since we dropped the rest earlier on)
        DBObject myDoc = testCollection.findOne();
        System.out.println(myDoc);

        // now, lets add lots of little documents to the collection so we can explore queries and cursors
        for (int i = 0; i < 100; i++) {
            testCollection.insert(new BasicDBObject().append("i", i));
        }
        System.out.println("total # of documents after inserting 100 small ones (should be 101) "
                + testCollection.getCount());

        //  lets get all the documents in the collection and print them out
        DBCursor cursor = testCollection.find();
        try {
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
        } finally {
            cursor.close();
        }

        //  now use a query to get 1 document out
        BasicDBObject query = new BasicDBObject("i", 71);
        cursor = testCollection.find(query);

        try {
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
        } finally {
            cursor.close();
        }

        //  now use a range query to get a larger subset
        query = new BasicDBObject("i", new BasicDBObject("$gt", 50)); // i.e. find all where i > 50
        cursor = testCollection.find(query);

        try {
            while (cursor.hasNext()) {
                System.out.println("Cursor: " + cursor.next());
            }
        } finally {
            cursor.close();
        }

        // range query with multiple constraints
        query = new BasicDBObject("i", new BasicDBObject("$gt", 20).append("$lte", 30)); // i.e.   20 < i <= 30
        cursor = testCollection.find(query);

        try {
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
        } finally {
            cursor.close();
        }

        // create an index on the "i" field
        testCollection.createIndex(new BasicDBObject("i", 1)); // create index on "i", ascending

        //  list the indexes on the collection
        List<DBObject> list = testCollection.getIndexInfo();
        for (DBObject o : list) {
            System.out.println(o);
        }

        // See if the last operation had an error
        System.out.println("Last error : " + db.getLastError());

        // see if any previous operation had an error
        System.out.println("Previous error : " + db.getPreviousError());

        // force an error
        db.forceError();

        // See if the last operation had an error
        System.out.println("Last error : " + db.getLastError());

        db.resetError();

        // release resources
        mongoClient.close();

    } catch (UnknownHostException ex) {
        Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
    }

    return print;

}

From source file:result.analysis.Analyze.java

int GetSubjectIndex(DBCollection collection, String sub_code) {
    DBObject obj = collection.findOne();

    List<BasicDBObject> docs = (List<BasicDBObject>) obj.get("result");
    int count = -1;
    for (BasicDBObject doc : docs) {
        count++;//from w w  w  .ja  va  2  s  .  c  o  m
        String sc = (String) doc.get("code");
        if (sc.equals(sub_code)) {
            return count;
        }
    }
    return -1;
}

From source file:result.analysis.Analyze.java

String[] GetSubCodes(DBCollection collection) {
    String[] codes;//  w w w . j  a  v  a  2s  .co  m
    DBObject t = collection.findOne();
    DBObject obj = collection.findOne();
    List<BasicDBObject> docs = (List<BasicDBObject>) obj.get("result");
    codes = new String[docs.size()];
    for (int i = 0; i < docs.size(); i++) {
        codes[i] = docs.get(i).getString("code");
    }
    return codes;

}

From source file:test.mongodb.servlet.MongoDBServlet.java

License:Open Source License

protected void tutorial(PrintWriter pw) {
    try {//from   w  ww .  j  a  va  2 s  . c  o m
        mongoDB.requestStart();
        pw.format("<h1>Tutorial Objects Added to DB</h1>\n");
        DBCollection coll = mongoDB.getCollection("testCollection");
        BasicDBObject doc = new BasicDBObject();

        doc.put("name", "MongoDB");
        doc.put("type", "database");
        doc.put("count", 1);

        BasicDBObject info = new BasicDBObject();

        info.put("x", 203);
        info.put("y", 102);

        doc.put("info", info);

        coll.insert(doc);
        DBObject myDoc = coll.findOne();
        pw.format("<h2>testCollection</h2><pre>%s</pre>\n", myDoc.toString());

        for (int i = 0; i < 100; i++) {
            coll.insert(new BasicDBObject().append("i", i));
        }

        BasicDBObject query = new BasicDBObject();
        query.put("i", 71);
        DBCursor cur = coll.find(query);
        pw.format("<h2>100 i objects, #71:</h2><pre>%s</pre>\n", cur.next());

        coll.createIndex(new BasicDBObject("i", 1)); // create index on "i", ascending
    } finally {
        mongoDB.requestDone();
    }
}