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(@Nullable final DBObject query, final DBCollectionFindOptions findOptions) 

Source Link

Document

Get a single document from collection.

Usage

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

@Override
public int viewFriendReq(int profileOwnerID, Vector<HashMap<String, ByteIterator>> values, boolean insertImage,
        boolean testMode) {
    int retVal = 0;
    if (profileOwnerID < 0)
        return -1;

    // first get all pending friendids for profileOwnerID
    com.mongodb.DB db = null;/*  ww w  .j  a  v a  2  s . com*/

    try {
        db = mongo.getDB(database);
        db.requestStart();
        DBCollection collection = db.getCollection("users");
        DBObject q = new BasicDBObject().append("_id", profileOwnerID);
        q.removeField("pic");
        BasicDBObject fields = new BasicDBObject("pic", 0);

        DBObject queryResult = null;
        queryResult = collection.findOne(q, fields);

        String x = queryResult.get("PendFriends").toString();
        if (!x.equals("")) {
            x = x.substring(2, x.length() - 1);
            if (!x.equals("")) {
                String friendIds[] = x.split(",");
                BasicDBObject query = new BasicDBObject();

                List<Integer> list = new ArrayList<Integer>();
                if (!friendListReq) {
                    int cnt = 0;
                    for (int i = 0; i < friendIds.length; i++) {
                        cnt++;
                        HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();
                        DBObject frnd = new BasicDBObject().append("_id",
                                Integer.parseInt(friendIds[i].trim()));
                        frnd.removeField("pic");
                        DBObject frndQueryResult = null;
                        frndQueryResult = collection.findOne(frnd, fields);
                        if (frndQueryResult.get("tpic") != null) {
                            byte[] myPic = (byte[]) frndQueryResult.get("tpic");
                            vals.put("tpic", new ObjectByteIterator(myPic));
                            if (testMode) {
                                // Save loaded image from database into new
                                // image file
                                FileOutputStream fos = new FileOutputStream(
                                        profileOwnerID + "-" + i + "-mthumbimage.bmp");
                                fos.write(myPic);
                                fos.close();
                            }
                            frndQueryResult.removeField("tpic");
                        }
                        if (frndQueryResult != null) {
                            frndQueryResult.removeField("ConfFriends");
                            frndQueryResult.removeField("PendFriends");
                            frndQueryResult.removeField("wallResources");
                            vals.putAll(frndQueryResult.toMap());
                        }
                        if (vals.get("_id") != null) {
                            String tmp = vals.get("_id") + "";
                            vals.remove("_id");
                            vals.put("userid", new ObjectByteIterator(tmp.getBytes()));
                        }
                        values.add(vals);
                    }
                } else if (friendListReq) {// retrive one list
                    for (int i = 0; i < friendIds.length; i++) {
                        // put all in one list and retrieve instead of
                        // retrieving one by one
                        list.add(Integer.parseInt(friendIds[i].trim()));
                    }
                    query.put("_id", new BasicDBObject("$in", list));
                    query.removeField("pic");
                    DBCursor cursor = collection.find(query, fields);
                    int cnt = 0;
                    while (cursor.hasNext()) {
                        cnt++;
                        // System.out.println(cursor.next());
                        HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();
                        DBObject curs = cursor.next();
                        if (curs.get("tpic") != null) {
                            byte[] myPic = (byte[]) curs.get("tpic");
                            vals.put("tpic", new ObjectByteIterator(myPic));
                            if (testMode) {
                                // Save loaded image from database into new
                                // image file
                                FileOutputStream fos = new FileOutputStream(
                                        profileOwnerID + "-" + cnt + "-mthumbimage.bmp");
                                fos.write(myPic);
                                fos.close();
                            }
                            curs.removeField("tpic");
                        }
                        vals.putAll(curs.toMap());
                        vals.remove("PendFriends");
                        vals.remove("ConfFriends");
                        vals.remove("wallResources");
                        // needed to do this so the coreworkload will not
                        // need to know the datastore typr
                        if (vals.get("_id") != null) {
                            String tmp = vals.get("_id") + "";
                            vals.remove("_id");
                            vals.put("userid", new ObjectByteIterator(tmp.getBytes()));
                        }
                        values.add(vals);
                    }
                    cursor.close();
                }

            }

        }

    } catch (Exception e) {
        System.out.println(e.toString());
        retVal = -1;
    } finally {
        if (db != null) {
            db.requestDone();
        }
    }
    return retVal;

}

From source file:net.autosauler.ballance.server.model.Currency.java

License:Apache License

/**
 * Find preivous currency value.//from  w w  w.j av a  2 s .co m
 * 
 * @param mnemo
 *            the mnemo
 * @param day
 *            the day
 * @return the dB object
 */
private static DBObject findPreivous(String mnemo, Date day) {
    Long toplimit = day.getTime();

    DBObject myDoc = null;
    DB db = Database.get(null);
    if (db != null) {
        DBCollection coll = db.getCollection(CURRENCYTABLE);
        BasicDBObject query = new BasicDBObject();
        query.put("timestamp", new BasicDBObject("$lt", toplimit));
        query.put("mnemo", mnemo);

        myDoc = coll.findOne(query, new BasicDBObject("$orderby", "timestamp"));
    }
    return myDoc;
}

From source file:org.apache.karaf.jaas.modules.mongo.internal.DefaultUserDetailService.java

License:Apache License

@Override
public UserInfo getUserInfo(String username) throws Exception {

    DB db = getDB();//from w w w . j  a v a2s . c  om

    DBCollection users = db.getCollection(configuration.getUserCollectionName());

    // populate user
    DBObject userQuery = new BasicDBObject("username", username);

    BasicDBObjectBuilder userProjectionBuilder = BasicDBObjectBuilder.start().add("_id", 0).add("username", 1)
            .add("passwordHash", 1);

    // also add all custom user fields
    for (String prop : configuration.getAdditionalAttributes()) {
        userProjectionBuilder.add(prop, 1);
    }

    DBObject user = users.findOne(userQuery, userProjectionBuilder.get());
    // if nothing comes back just return empty handed
    if (user == null) {
        return null;
    }

    UserInfo userInfo = new UserInfo().withName((String) user.get("username"))
            .withPassword((String) user.get("passwordHash"));

    for (String prop : configuration.getAdditionalAttributes()) {

        // only add if property is actually present in the database
        if (user.containsField(prop)) {
            Object val = user.get(prop);
            userInfo.addProperty(prop, val != null ? val.toString() : "");
        }

    }

    // populate group
    DBCollection groups = db.getCollection(configuration.getGroupCollectionName());

    DBObject groupQuery = new BasicDBObject("members", username);

    DBCursor gc = groups.find(groupQuery,
            BasicDBObjectBuilder.start().append("_id", 0).append("name", 1).get());

    while (gc.hasNext()) {
        DBObject group = gc.next();
        userInfo.addGroup((String) group.get("name"));
    }
    gc.close();

    return userInfo;

}

From source file:org.basex.modules.MongoDB.java

License:BSD License

/**
 * findOne with query and projection projection.
 * @param handler//from   w ww .  ja v  a  2  s.  c o  m
 * @param col
 * @param query
 * @param field
 * @return Item
 * @throws QueryException
 */
public Item findOne(final Str handler, final Item col, final Item query, final Item projection)
        throws QueryException {

    final DB db = getDbHandler(handler);
    db.requestStart();
    try {
        final DBObject p = projection != null ? getDbObjectFromStr(projection) : null;
        final DBObject q = query != null ? getDbObjectFromStr(query) : null;
        final DBCollection coll = db.getCollection(itemToString(col));
        final DBObject cursor = coll.findOne(q, p);
        return objectToItem(handler, cursor);
    } catch (MongoException e) {
        throw MongoDBErrors.generalExceptionError(e.getMessage());
    } finally {
        db.requestDone();
    }
}

From source file:org.basex.modules.nosql.MongoDB.java

License:BSD License

/**
 * findOne with query and projection projection.
 * @param handler database handler/*from  www  . jav  a 2  s  .co  m*/
 * @param col collection
 * @param query selection query
 * @param projection  projection
 * @return Item
 * @throws QueryException query exception
 */
public Item findOne(final Str handler, final Item col, final Item query, final Item projection)
        throws QueryException {

    final DB db = getDbHandler(handler);
    db.requestStart();
    try {
        final DBObject p = projection != null ? getDbObjectFromItem(projection) : null;
        final DBObject q = query != null ? getDbObjectFromItem(query) : null;
        final DBCollection coll = db.getCollection(itemToString(col));
        final DBObject cursor = coll.findOne(q, p);
        return objectToItem(handler, cursor);
    } catch (MongoException e) {
        throw MongoDBErrors.generalExceptionError(e.getMessage());
    } finally {
        db.requestDone();
    }
}

From source file:org.fastmongo.odm.bson.repository.BsonMongoTemplate.java

License:Apache License

private byte[] doFindOne(String collectionName, Query query, Query fields) {
    DBCollection collection = getCollection(collectionName);
    DBObject db = collection.findOne(query.toDbObject(), fields != null ? fields.toDbObject() : null);
    if (db == null) {
        return null;
    }// ww w .  j av a2 s. com

    return getData(db);
}

From source file:org.fastmongo.odm.bson.repository.BsonMongoTemplate.java

License:Apache License

/**
 * Returns a {@link com.mongodb.BasicDBObject}.
 *
 * @param clazz      the collection class.
 * @param query      specifies the selection criteria (<tt>nullable</tt>).
 * @param projection specified the fields of document to include/exclude.
 * @return the {@link com.mongodb.BasicDBObject}.
 *//*from w  w w. jav a 2s .co  m*/
public DBObject findAsDbObject(final Class<?> clazz, final Query query, final Projection projection) {
    DBCollection collection = getCollection(clazz);
    DBObject db = collection.findOne(query != null ? query.toDbObject() : null,
            projection != null ? projection.toDbObject() : null);
    return toDbObject(db);
}

From source file:org.jivesoftware.openfire.vcard.DefaultVCardProvider.java

License:Open Source License

public Element loadVCard(String username) {

    synchronized (username.intern()) {
        if (db == null) {
            db = MongoDbConnectionManager.reconnect();
        }//from  w w  w .java2s . c om
        if (db == null)
            return null;

        Element vCardElement = null;

        SAXReader xmlReader = null;
        try {

            DBCollection coll = db.getCollection("gUser");
            BasicDBObject doc = new BasicDBObject("photoId", 1).append("vcard", 1);

            BasicDBObject q = new BasicDBObject("himId", username);
            DBObject res = coll.findOne(q, doc);

            if (res != null) {
                BasicDBObject photo = (BasicDBObject) res.get("photoId");
                BasicDBObject vcardXml = (BasicDBObject) res.get("vcard");
                if (vcardXml != null) {
                    vCardElement = new DOMElement("vCard", new Namespace(null, "vcard-temp-ext"));
                    String url = (String) vcardXml.getString("url");
                    Element urlE = new DOMElement("url");
                    Element type = new DOMElement("type");
                    type.setText((String) vcardXml.getString("type"));
                    urlE.setText(url);
                    vCardElement.add(urlE);
                } else if (photo != null) {
                    Element photoEl = new DOMElement("PHOTO");
                    Element bin = new DOMElement("BINVAL");
                    Element type = new DOMElement("type");
                    vCardElement = new DOMElement("vCard", new Namespace(null, "vcard-temp"));
                    String url = (String) photo.getString("url");
                    type.setText(photo.getString("contentType"));
                    HttpClient client = new HttpClient();
                    GetMethod method = new GetMethod(url);
                    client.executeMethod(method);
                    if (method.getStatusCode() == HttpStatus.SC_OK) {
                        InputStream ios = method.getResponseBodyAsStream();
                        byte[] data = new byte[2048];
                        int len = 0;
                        StringBuilder builder = new StringBuilder();
                        while ((len = ios.read(data)) != -1) {
                            builder.append(Base64.encodeBytes(data, 0, len, Base64.NO_OPTIONS));
                        }
                        bin.setText(builder.toString());
                        ios.close();
                    }
                    photoEl.add(type);
                    photoEl.add(bin);
                    vCardElement.add(photoEl);
                }

            }

        } catch (Exception e) {
            Log.error("Error loading vCard of username: " + username, e);
        } finally {

        }
        return vCardElement;
    }
}

From source file:org.kiaan.Main.java

private static void getBuy() {
    try {/*from  w  w w  . ja  va  2 s.c o m*/
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        DB db = mongoClient.getDB("kiaan");
        DBCollection coll = db.getCollection("buy");
        //aggregate
        DBObject unwind = new BasicDBObject("$unwind", "$items");
        //$group            
        DBObject group_id = new BasicDBObject("_id", "$_id");
        group_id.put("num", "$num");
        group_id.put("person_id", "$person_id");
        group_id.put("discount", "$discount");
        group_id.put("increase", "$increase");
        //$group -> $multiply
        BasicDBList args = new BasicDBList();
        args.add("$items.value");
        args.add("$items.price");
        DBObject multiply = new BasicDBObject("$multiply", args);
        //$group -> $sum
        //            DBObject group_sum = new BasicDBObject("$sum", multiply);
        DBObject group_field = new BasicDBObject();
        group_field.put("_id", group_id);
        group_field.put("total", new BasicDBObject("$sum", multiply));
        DBObject group = new BasicDBObject("$group", group_field);
        //$project
        DBObject project_field = new BasicDBObject("_id", "$_id._id");
        project_field.put("person_id", "$_id.person_id");
        project_field.put("num", "$_id.num");
        BasicDBList arr = new BasicDBList();
        arr.add("$total");
        arr.add("$_id.discount");
        arr.add("$_id.increase");
        DBObject field_add = new BasicDBObject("$add", arr);
        project_field.put("sum", field_add);
        DBObject project = new BasicDBObject("$project", project_field);
        DBObject sort = new BasicDBObject("$sort", new BasicDBObject("_id", 1));
        List<DBObject> pipeline = Arrays.asList(unwind, group, project, sort);

        //            AggregationOutput output = coll.aggregate(pipeline);
        //            for (DBObject result : output.results()) {
        //                System.out.println(result);
        //            }

        AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100)
                .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build();

        BasicDBObject dbo = new BasicDBObject();
        BasicDBList dbl = new BasicDBList();
        Cursor cursor = coll.aggregate(pipeline, aggregationOptions);
        //
        DBCollection person_col = db.getCollection("persons");

        //            BasicDBObject query = new BasicDBObject("items.personId",1);             
        BasicDBObject fields = new BasicDBObject("items.$", 1).append("_id", false);

        //            BasicDBList l_per = (BasicDBList) person_col.findOne(query, fields).get("items");
        //            BasicDBObject[] lightArr = l_per.toArray(new BasicDBObject[0]);            
        //            System.out.println(lightArr[0].get("_id"));
        //            System.out.println(lightArr[0].get("first_name"));  

        BasicDBList result = new BasicDBList();
        while (cursor.hasNext()) {
            dbo = (BasicDBObject) cursor.next();
            //                System.out.println(dbo.toString());  
            DBObject query = new BasicDBObject("items._id", (ObjectId) dbo.get("person_id"));
            BasicDBList lst_person = (BasicDBList) person_col.findOne(query, fields).get("items");
            BasicDBObject[] lightArr = lst_person.toArray(new BasicDBObject[0]);
            //                System.out.println(lightArr[0].get("first_name"));

            Date date = ((ObjectId) lightArr[0].get("_id")).getDate();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            persianCalendar persianCalendar = new persianCalendar(calendar);

            dbo.put("date", persianCalendar.getNumericDateFormatWithTime());
            dbo.put("personId", lightArr[0].get("personId").toString());
            dbo.put("first_name", lightArr[0].get("first_name").toString());
            dbo.put("last_name", lightArr[0].get("last_name").toString());

            dbo.removeField("person_id");
            result.add(dbo);
            //                System.out.println(dbo.get("num"));                  
        }
        System.out.println(result.toString());

    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
}

From source file:org.vertx.mods.MongoPersistor.java

License:Apache License

private void doFindOne(Message<JsonObject> message) {
    String collection = getMandatoryString("collection", message);
    if (collection == null) {
        return;/*from  w  w  w. ja va2  s  . c  o  m*/
    }
    JsonObject matcher = message.body.getObject("matcher");
    JsonObject keys = message.body.getObject("keys");
    DBCollection coll = db.getCollection(collection);
    DBObject res;
    if (matcher == null) {
        res = keys != null ? coll.findOne(null, jsonToDBObject(keys)) : coll.findOne();
    } else {
        res = keys != null ? coll.findOne(jsonToDBObject(matcher), jsonToDBObject(keys))
                : 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);
}