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(final Object id) 

Source Link

Document

Get a single document from collection by '_id'.

Usage

From source file:models.datasource.SingletonDataSource.java

public static User getUserByEmail(String email) {
    DBCollection collection = connectDB("mongo.usersCollection");
    BasicDBObject query = new BasicDBObject().append("email", email);
    DBObject dbObject = collection.findOne(query);

    if (dbObject != null) {
        User user = new User();
        String userStr = dbObject.toString();

        //Get user object from JSON
        user = new Gson().fromJson(userStr, User.class);

        if (user.emailVerificationKey != null) {
            return null;
        }/*w ww.  j  a va2s.com*/

        // Deserialize Current Situation object
        user.currentSituation = new Gson().fromJson(dbObject.get(Constants.USER_CURRENT_SITUATION).toString(),
                CurrentSituation.class);

        // Deserialize ArrayList of Skills
        user.skill = new Gson().fromJson(dbObject.get(Constants.USER_SKILLS_LIST).toString(),
                new TypeToken<List<Skill>>() {
                }.getType());

        //Add to USER the completedOrientationSteps object stored in JSON
        user.completedOrientationSteps = new Gson().fromJson(
                dbObject.get(Constants.USER_ORIENTATION_STEPS).toString(),
                User.CompletedOrientationSteps.class);
        // Deserialize ArrayList of InterviewSchedule Objects
        user.interviewScheduleList = new Gson().fromJson(
                dbObject.get(Constants.USER_NEXT_INTERVIEWS_LIST).toString(),
                new TypeToken<List<InterviewSchedule>>() {
                }.getType());

        // Deserialize ArrayList of Courses
        user.courses = new Gson().fromJson(dbObject.get(Constants.USER_COURSES).toString(),
                new TypeToken<List<Course>>() {
                }.getType());

        //Deserialize ArrayList of Languages
        user.languages = new Gson().fromJson(dbObject.get(Constants.USER_LANGUAGES).toString(),
                new TypeToken<List<Language>>() {
                }.getType());

        //Deserialize ArrayList of Software
        user.softwareList = new Gson().fromJson(dbObject.get(Constants.USER_SOFTWARE).toString(),
                new TypeToken<List<Software>>() {
                }.getType());

        user.id = dbObject.get("_id").toString();

        mongoClient.close();
        return user;
    } else {
        mongoClient.close();
        return null;
    }
}

From source file:models.datasource.SingletonDataSource.java

public static User validateUser(String email, String emailVerificationKey) {
    DBCollection collection = connectDB("mongo.usersCollection");
    BasicDBObject query = new BasicDBObject().append("email", email);
    DBObject dbObject = collection.findOne(query);

    if (dbObject != null) {
        User user = new User();
        String userStr = dbObject.toString();

        //Get user object from JSON
        user = new Gson().fromJson(userStr, User.class);

        // Deserialize Current Situation object
        user.currentSituation = new Gson().fromJson(dbObject.get(Constants.USER_CURRENT_SITUATION).toString(),
                CurrentSituation.class);

        // Deserialize ArrayList of Skills
        user.skill = new Gson().fromJson(dbObject.get(Constants.USER_SKILLS_LIST).toString(),
                new TypeToken<List<Skill>>() {
                }.getType());//from ww  w . j  a v a 2 s .  c o m

        //Add to USER the completedOrientationSteps object stored in JSON
        user.completedOrientationSteps = new Gson().fromJson(
                dbObject.get(Constants.USER_ORIENTATION_STEPS).toString(),
                User.CompletedOrientationSteps.class);
        // Deserialize ArrayList of InterviewSchedule Objects
        user.interviewScheduleList = new Gson().fromJson(
                dbObject.get(Constants.USER_NEXT_INTERVIEWS_LIST).toString(),
                new TypeToken<List<InterviewSchedule>>() {
                }.getType());

        // Deserialize ArrayList of Courses
        user.courses = new Gson().fromJson(dbObject.get(Constants.USER_COURSES).toString(),
                new TypeToken<List<Course>>() {
                }.getType());

        //Deserialize ArrayList of Languages
        user.languages = new Gson().fromJson(dbObject.get(Constants.USER_LANGUAGES).toString(),
                new TypeToken<List<Language>>() {
                }.getType());

        //Deserialize ArrayList of Software
        user.softwareList = new Gson().fromJson(dbObject.get(Constants.USER_SOFTWARE).toString(),
                new TypeToken<List<Software>>() {
                }.getType());

        user.id = dbObject.get("_id").toString();

        if (user.emailVerificationKey != null && user.emailVerificationKey.equals(emailVerificationKey)) {
            //user.emailVerificationKey = null;
            mongoClient.close();
            return user;
        } else {
            mongoClient.close();
            return null;
        }
    } else {
        mongoClient.close();
        return null;
    }
}

From source file:models.datasource.SingletonDataSource.java

public static void updateUserData(String email, String key, String newValue) {
    DBCollection collection = connectDB("mongo.usersCollection");
    BasicDBObject query = new BasicDBObject().append("email", email);
    DBObject user = collection.findOne(query);

    if (user != null) {
        BasicDBObject updateQuery = new BasicDBObject().append("$set",
                new BasicDBObject().append(key, newValue));
        collection.update(query, updateQuery);
    }/* w ww.j a v  a2s .c  o m*/
    mongoClient.close();
}

From source file:models.datasource.SingletonDataSource.java

public static boolean deleteUser(String email) {
    DBCollection collection = connectDB("mongo.usersCollection");
    BasicDBObject query = new BasicDBObject().append("email", email);
    DBObject dbObject = collection.findOne(query);
    if (dbObject != null) {
        collection.remove(dbObject);/*from   w  w  w.  j  ava  2s . c  o m*/
        mongoClient.close();
        return true;
    } else {
        mongoClient.close();
        return false;
    }
}

From source file:mongodb.JavaDocSave.java

public static void saveBlueDoc(DBCollection collection) {
    BasicDBObject query = new BasicDBObject("word", "ocean");
    DBObject word = collection.findOne(query);
    word.put("category", "blue");
    WriteResult result = collection.save(word);
    System.out.println("Update Result: \n" + result.toString());
}

From source file:mongodb.JavaDocSave.java

public static void resetDoc(DBCollection collection) {
    BasicDBObject query = new BasicDBObject("word", "ocean");
    DBObject word = collection.findOne(query);
    word.put("category", "");
    WriteResult result = collection.save(word);
    System.out.println("Update Result: \n" + result.toString());
}

From source file:mongodb.JavaDocUpsert.java

public static void showWord(DBCollection collection, String msg) {
    System.out.println("\n" + msg + ": ");
    BasicDBObject query = new BasicDBObject("word", "righty");
    DBObject doc = collection.findOne(query);
    System.out.println(doc);/*  w  w  w . jav  a  2  s.  c o  m*/
}

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

@Override
/**/*from   w  w w.ja v  a 2  s. c  o m*/
 * Insert a record in the database. Any field/value pairs in the specified values HashMap will be written into the record with the specified
 * record key.
 *
 * @param entitySet The name of the table
 * @param entityPK The record key of the record to insert.
 * @param values A HashMap of field/value pairs to insert in the record
 * @return Zero on success, a non-zero error code on error. See this class's description for a discussion of error codes.
 */
public int insertEntity(String entitySet, String entityPK, HashMap<String, ByteIterator> values,
        boolean insertImage) {
    com.mongodb.DB db = null;
    WriteResult res = null;
    try {
        // get the appropriate database
        db = mongo.getDB(database);
        // ensure order
        db.requestStart();
        // appropriate table - collection
        DBCollection collection = db.getCollection(entitySet);
        // create the row-object-document
        // need to insert key as integer else the sorting based on id for
        // topk s wont happen properly

        DBObject r = new BasicDBObject().append("_id", Integer.parseInt(entityPK));
        for (String k : values.keySet()) {
            if (!(k.toString().equalsIgnoreCase("pic") || k.toString().equalsIgnoreCase("tpic")))
                r.put(k, values.get(k).toString());
        }

        if (entitySet.equalsIgnoreCase("users")) {
            // ArrayList x = new ArrayList();
            r.put("ConfFriends", new ArrayList<Integer>());
            r.put("PendFriends", new ArrayList<Integer>());
            r.put("wallResources", new ArrayList<Integer>());
        }

        if (entitySet.equalsIgnoreCase("users") && insertImage) {
            // insert picture separately
            // create one gridFS for the datastore
            byte[] profileImage = ((ObjectByteIterator) values.get("pic")).toArray();
            r.put("pic", profileImage);
            // create the thumbnail image
            /*
             * File file = new File("mypic.jpg"); byte fileContent[] = null;
             * try{ //create FileInputStream object FileInputStream fin =
             * new FileInputStream(file); fileContent = new
             * byte[(int)file.length()]; fin.read(fileContent);
             * }catch(Exception e){ e.printStackTrace(); } byte[] thumbImage
             * = fileContent;
             */

            byte[] thumbImage = ((ObjectByteIterator) values.get("tpic")).toArray();
            r.put("tpic", thumbImage);

        }

        res = collection.insert(r, writeConcern);

        if (entitySet.equalsIgnoreCase("resources")) {
            // add the rid to the walluserids profile
            collection = db.getCollection("users");
            DBObject q = new BasicDBObject().append("_id", Integer.parseInt((String) r.get("walluserid")));
            DBObject queryResult = null;
            queryResult = collection.findOne(q);
            String x = queryResult.get("wallResources").toString();
            BasicDBObject updateCommand = new BasicDBObject();
            if (!x.equals("[ ]")) {
                x = x.substring(1, x.length() - 1);
                String resourceIds[] = x.split(",");
                int[] resIds = new int[resourceIds.length + 1];
                for (int i = 0; i < resourceIds.length; i++) { // to limit
                    // it
                    resIds[i] = Integer.parseInt(resourceIds[i].trim());
                }
                resIds[resourceIds.length] = Integer.parseInt(r.get("_id").toString());
                Arrays.sort(resIds);
                updateCommand.put("$set", new BasicDBObject("wallResources", resIds));
            } else
                updateCommand.put("$push", new BasicDBObject("wallResources", r.get("_id")));
            res = collection.update(q, updateCommand, false, false, writeConcern);
        }

        /*
         * // test to see if inserted - search query BasicDBObject
         * searchQuery = new BasicDBObject(); searchQuery.put("_id",
         * Integer.parseInt(key)); // query it DBCursor cursor =
         * collection.find(searchQuery); // loop over the cursor and display
         * the retrieved result while (cursor.hasNext()) {
         * System.out.println(cursor.next()); } return 0;
         */
    } catch (Exception e) {
        System.out.println(e.toString());
        return -1;
    } finally {
        if (db != null) {
            db.requestDone();
        }
    }
    return res.getError() == null ? 0 : -1;
}

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

@Override
public int viewTopKResources(int requesterID, int profileOwnerID, int k,
        Vector<HashMap<String, ByteIterator>> result) {
    int retVal = 0;
    if (profileOwnerID < 0 || requesterID < 0 || k < 0)
        return -1;

    com.mongodb.DB db = null;//from www. j  av a2 s  .  c o  m

    try {
        db = mongo.getDB(database);
        db.requestStart();
        if (scanResources) {
            DBCollection collection = db.getCollection("resources");
            // find all resources that belong to profileOwnerID
            // sort them by _id desc coz we want latest ones and get the top
            // k
            DBObject q = new BasicDBObject().append("walluserid", Integer.toString(profileOwnerID));
            DBCursor queryResult = null;
            queryResult = collection.find(q);
            // DBObject s = new BasicDBObject().append("_id", -1); //desc
            DBObject s = new BasicDBObject(); // desc
            s.put("_id", -1);
            queryResult = queryResult.sort(s);
            queryResult = queryResult.limit(k);
            Iterator it = queryResult.iterator();
            while (it.hasNext()) {
                HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();
                DBObject oneRes = new BasicDBObject();
                oneRes.putAll((DBObject) it.next());
                vals.putAll(oneRes.toMap());
                // needed to do this so the coreworkload will not need to
                // know the datastore type
                if (vals.get("_id") != null) {
                    String tmp = vals.get("_id") + "";
                    vals.remove("_id");
                    vals.put("rid", new ObjectByteIterator(tmp.getBytes()));
                }
                if (vals.get("walluserid") != null) {
                    String tmp = vals.get("walluserid") + "";
                    vals.remove("walluserid");
                    vals.put("walluserid", new ObjectByteIterator(tmp.getBytes()));
                }
                if (vals.get("creatorid") != null) {
                    String tmp = vals.get("creatorid") + "";
                    vals.remove("creatorid");
                    vals.put("creatorid", new ObjectByteIterator(tmp.getBytes()));
                }
                result.add(vals);
            }
            queryResult.close();

        } else {
            DBCollection collection = db.getCollection("users");
            DBObject q = new BasicDBObject().append("_id", profileOwnerID);
            DBObject queryResult = null;
            queryResult = collection.findOne(q);
            String x = queryResult.get("wallResources").toString();
            if (!x.equals("[ ]")) {
                x = x.substring(1, x.length() - 1);
                String resourceIds[] = x.split(",");
                BasicDBObject query = new BasicDBObject();
                List<Integer> list = new ArrayList<Integer>();
                for (int i = resourceIds.length - 1; i >= resourceIds.length
                        - Math.min(k, resourceIds.length); i--) { // to
                    // limit
                    // it
                    list.add(Integer.parseInt(resourceIds[i].trim()));
                }
                collection = db.getCollection("resources");
                query.put("_id", new BasicDBObject("$in", list));
                DBCursor cursor = collection.find(query);
                while (cursor.hasNext()) {
                    HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();
                    vals.putAll(cursor.next().toMap());
                    if (vals.get("_id") != null) {
                        String tmp = vals.get("_id") + "";
                        vals.remove("_id");
                        vals.put("rid", new ObjectByteIterator(tmp.getBytes()));
                    }
                    if (vals.get("walluserid") != null) {
                        String tmp = vals.get("walluserid") + "";
                        vals.remove("walluserid");
                        vals.put("walluserid", new ObjectByteIterator(tmp.getBytes()));
                    }
                    if (vals.get("creatorid") != null) {
                        String tmp = vals.get("creatorid") + "";
                        vals.remove("creatorid");
                        vals.put("creatorid", new ObjectByteIterator(tmp.getBytes()));
                    }
                    result.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:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

@Override
public int viewCommentOnResource(int requesterID, int profileOwnerID, int resourceID,
        Vector<HashMap<String, ByteIterator>> result) {
    int retVal = 0;
    if (profileOwnerID < 0 || requesterID < 0 || resourceID < 0)
        return -1;

    com.mongodb.DB db = null;/*from   w  w  w . j  av a2  s  . c  o  m*/

    try {
        db = mongo.getDB(database);
        db.requestStart();
        if (!manipulationArray) {
            DBCollection collection = db.getCollection("manipulation");
            // find all resources that belong to profileOwnerID
            // sort them by _id desc coz we want latest ones and get the top
            // k
            DBObject q = new BasicDBObject().append("rid", Integer.toString(resourceID));
            DBCursor queryResult = null;
            queryResult = collection.find(q);
            Iterator<DBObject> it = queryResult.iterator();
            while (it.hasNext()) {
                HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();
                DBObject oneRes = new BasicDBObject();
                oneRes.putAll((DBObject) it.next());
                vals.putAll(oneRes.toMap());
                result.add(vals);
            }
            queryResult.close();
        } else {
            DBCollection collection = db.getCollection("resources");
            DBObject q = new BasicDBObject().append("_id", resourceID);
            DBObject queryResult = null;
            queryResult = collection.findOne(q);
            if (queryResult.get("Manipulations") != "" && queryResult.get("Manipulations") != null) {
                ArrayList<DBObject> mans = (ArrayList<DBObject>) queryResult.get("Manipulations");
                for (int i = 0; i < mans.size(); i++) {
                    result.add((HashMap<String, ByteIterator>) mans.get(i).toMap());
                }
            }
        }

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