List of usage examples for com.mongodb DBCollection findOne
@Nullable public DBObject findOne(@Nullable final DBObject query, final DBCollectionFindOptions findOptions)
From source file:com.softinstigate.restheart.db.DBDAO.java
License:Open Source License
/** * * @param dbName//from w w w. jav a2s . co m * @param requestEtag * @return */ public static int deleteDB(String dbName, ObjectId requestEtag) { DB db = DBDAO.getDB(dbName); DBCollection coll = db.getCollection("_properties"); BasicDBObject checkEtag = new BasicDBObject("_id", "_properties"); checkEtag.append("_etag", requestEtag); DBObject exists = coll.findOne(checkEtag, fieldsToReturn); if (exists == null) { return HttpStatus.SC_PRECONDITION_FAILED; } else { db.dropDatabase(); return HttpStatus.SC_NO_CONTENT; } }
From source file:com.softlyinspired.jlw.script.validationScript.java
License:Open Source License
/** * returns a scriptId/*from ww w .java2 s.c o m*/ * @param MenuId * @throws UnknownHostException */ private int readMongoMenuScriptId(int MenuId) throws UnknownHostException { int scriptId = -1; DBCollection coll = repoConnection.getScriptCollection(); BasicDBObject query = new BasicDBObject(); BasicDBObject fields = new BasicDBObject(); query.put("menuId", MenuId); fields.put("scriptIds", 1); fields.put("_id", 0); try { DBObject scriptIdQuery = coll.findOne(query, fields); scriptId = Integer.parseInt(scriptIdQuery.get("scriptIds").toString()); } catch (Exception e) { JLWUtilities.scriptErrorMessage("Error fetching mongo script"); } return scriptId; }
From source file:com.softlyinspired.jlw.script.validationScript.java
License:Open Source License
/** * Gets the full details of the script using the script id * @param ScriptId//from w w w.ja va 2s . c om * @return * @throws UnknownHostException */ private int readMongoScript(int ScriptId) throws UnknownHostException { //String scriptText = new String(); int errorId = 0; DBCollection coll = repoConnection.getScriptCollection(); BasicDBObject query = new BasicDBObject(); BasicDBObject fields = new BasicDBObject(); query.put("scriptId", ScriptId); fields.put("scriptText", 1); fields.put("ScriptCategory", 1); fields.put("scriptTitle", 1); fields.put("scriptConnection", 1); fields.put("_id", 0); try { DBObject customQuery = coll.findOne(query, fields); try { currentScriptText = customQuery.get("scriptText").toString(); } catch (Exception e) { currentScriptText = "unknown"; } try { currentScriptCategory = customQuery.get("ScriptCategory").toString(); } catch (Exception e) { currentScriptCategory = "unknown"; } try { currentScriptTitle = customQuery.get("scriptTitle").toString(); } catch (Exception e) { currentScriptTitle = "unknown"; } try { currentConnection = customQuery.get("scriptConnection").toString(); } catch (Exception e) { currentConnection = "unknown"; } } finally { } return errorId; }
From source file:edu.umass.cs.gnsserver.database.MongoRecords.java
License:Apache License
@Override public HashMap<ColumnField, Object> lookupSomeFields(String collectionName, String guid, ColumnField nameField, ColumnField valuesMapField, ArrayList<ColumnField> valuesMapKeys) throws RecordNotFoundException, FailedDBOperationException { if (guid == null) { DatabaseConfig.getLogger().log(Level.FINE, "{0} GUID is null: {1}", new Object[] { dbName, guid }); throw new RecordNotFoundException(guid); }//ww w.jav a 2 s .c o m db.requestStart(); try { String primaryKey = mongoCollectionSpecs.getCollectionSpec(collectionName).getPrimaryKey().getName(); db.requestEnsureConnection(); DBCollection collection = db.getCollection(collectionName); BasicDBObject query = new BasicDBObject(primaryKey, guid); BasicDBObject projection = new BasicDBObject().append("_id", 0); if (valuesMapField != null && valuesMapKeys != null) { for (int i = 0; i < valuesMapKeys.size(); i++) { String fieldName = valuesMapField.getName() + "." + valuesMapKeys.get(i).getName(); projection.append(fieldName, 1); } } DBObject dbObject = collection.findOne(query, projection); if (dbObject == null) { throw new RecordNotFoundException(guid); } HashMap<ColumnField, Object> hashMap = new HashMap<>(); hashMap.put(nameField, guid);// put the name in the hashmap!! very important!! if (valuesMapField != null && valuesMapKeys != null) { // first we pull all the user values from the dbObject and put in a bson object // FIXME: Why not convert this to a JSONObject right now? We know that's what it is. BasicDBObject bson = (BasicDBObject) dbObject.get(valuesMapField.getName()); DatabaseConfig.getLogger().log(Level.FINER, "{0} @@@@@@@@ {1}", new Object[] { dbName, bson }); // then we run thru each userkey in the valuesMapKeys and pull the // value put stuffing it into the values map ValuesMap valuesMap = new ValuesMap(); for (int i = 0; i < valuesMapKeys.size(); i++) { String userKey = valuesMapKeys.get(i).getName(); if (containsFieldDotNotation(userKey, bson) == false) { DatabaseConfig.getLogger().log(Level.FINE, "{0} DBObject doesn't contain {1}", new Object[] { dbName, userKey }); continue; } try { switch (valuesMapKeys.get(i).type()) { case USER_JSON: Object value = getWithDotNotation(userKey, bson); DatabaseConfig.getLogger().log(Level.FINE, "{0} Object is {1}", new Object[] { dbName, value.toString() }); valuesMap.put(userKey, value); break; case LIST_STRING: valuesMap.putAsArray(userKey, JSONUtils.JSONArrayToResultValue( new JSONArray(getWithDotNotation(userKey, bson).toString()))); break; default: DatabaseConfig.getLogger().log(Level.SEVERE, "{0} ERROR: Error: User keys field {1} is not a known type: {2}", new Object[] { dbName, userKey, valuesMapKeys.get(i).type() }); break; } } catch (JSONException e) { DatabaseConfig.getLogger().log(Level.SEVERE, "{0} Error parsing json: {1}", new Object[] { dbName, e.getMessage() }); e.printStackTrace(); } } hashMap.put(valuesMapField, valuesMap); } return hashMap; } catch (MongoException e) { DatabaseConfig.getLogger().log(Level.FINE, "{0} lookupSomeFields failed: {1}", new Object[] { dbName, e.getMessage() }); throw new FailedDBOperationException(collectionName, guid, "Original mongo exception:" + e.getMessage()); } finally { db.requestDone(); } }
From source file:essex.bigessexnew.OplogListener.java
private String retrieveContent(DBCollection realCollection, String id) { BasicDBObject query = new BasicDBObject(); query.put("_id", new ObjectId(id)); BasicDBObject fields = new BasicDBObject(); fields.put("_id", 0); fields.put("content", 1); return realCollection.findOne(query, fields).get("content").toString(); }
From source file:kiaanfx.Kiaanfx.java
private static void getBuy() { try {/* w w w. j av a2 s . c om*/ 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()); data.add(new Person(dbo.get("num").toString(), dbo.get("date").toString(), dbo.get("personId").toString(), dbo.get("first_name").toString(), dbo.get("last_name").toString())); // buy_data.add(new buys(dbo.get("num").toString(), // dbo.get("date").toString(), // dbo.get("personId").toString(), // dbo.get("first_name").toString(), // dbo.get("last_name").toString(), // dbo.get("sum").toString() // )); dbo.remove("person_id"); // result.add(dbo); // System.out.println(dbo.get("first_name")); } System.out.println(dbo.toString()); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } }
From source file:MDBInt.DBMongo.java
License:Apache License
public DBObject getFirstCountry(String tenant, DBObject shape) { //{"geometry": {$geoIntersects: {$geometry: { "coordinates" : [ 15.434675, 38.193164 ], "type" : "Point" }}}} DB database = this.getDB(tenant); DBCollection collection = database.getCollection("Countries"); DBObject result;//from w ww .j av a2s . c om BasicDBObject geometry = new BasicDBObject("$geometry", shape); BasicDBObject geoSpazialOperator = new BasicDBObject("$geoIntersects", geometry); BasicDBObject query = new BasicDBObject("geometry", geoSpazialOperator); BasicDBObject constrains = new BasicDBObject("_id", 0); Iterator<DBObject> it; result = collection.findOne(query, constrains); return result; }
From source file:mongodb.JavaDocSave.java
public static void showWord(DBCollection collection, String msg) { System.out.println("\n" + msg + ": "); BasicDBObject query = new BasicDBObject("word", "ocean"); BasicDBObject fields = new BasicDBObject("word", 1); fields.append("category", 1); DBObject doc = collection.findOne(query, fields); System.out.println(doc);/* w w w . ja v a2s . com*/ }
From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java
License:Open Source License
@Override public int viewProfile(int requesterID, int profileOwnerID, HashMap<String, ByteIterator> result, boolean insertImage, boolean testMode) { int retVal = 0; if (requesterID < 0 || profileOwnerID < 0) return -1; com.mongodb.DB db = null;/* w w w . j a v a 2s .co m*/ try { db = mongo.getDB(database); db.requestStart(); DBCollection collection = db.getCollection("users"); DBObject q = new BasicDBObject().append("_id", profileOwnerID); q.removeField("tpic"); BasicDBObject attrs = new BasicDBObject("tpic", 0); DBObject queryResult = null; queryResult = collection.findOne(q, attrs); if (queryResult.get("pic") != null) { byte[] myPic = (byte[]) queryResult.get("pic"); result.put("pic", new ObjectByteIterator(myPic)); if (testMode) { // Save loaded image from database into new image file FileOutputStream fos = new FileOutputStream(profileOwnerID + "--proimage.bmp"); fos.write(myPic); fos.close(); } queryResult.removeField("pic"); } String x = queryResult.get("ConfFriends").toString(); int frndCount = 0; if (x.equals("") || (!x.equals("") && (x.substring(2, x.length() - 1)).equals(""))) frndCount = 0; else { x = x.substring(2, x.length() - 1); frndCount = x.split(",").length; } int pendCount = 0; if (requesterID == profileOwnerID) { x = queryResult.get("PendFriends").toString(); if (x.equals("") || (!x.equals("") && (x.substring(2, x.length() - 1)).equals(""))) pendCount = 0; else { x = x.substring(2, x.length() - 1); pendCount = x.split(",").length; } } // find number of resources posted for the user // queryResult = null; // queryResult = collection.findOne(q); x = queryResult.get("wallResources").toString(); int resCount = 0; if (x.equals("")) resCount = 0; else { resCount = x.split(",").length; } if (queryResult != null) { // remove the ConfFriends and PendFriends and Resources // replace them with counts queryResult.removeField("ConfFriends"); queryResult.removeField("PendFriends"); queryResult.removeField("wallResources"); result.putAll(queryResult.toMap()); result.put("friendcount", new ObjectByteIterator(Integer.toString(frndCount).getBytes())); if (requesterID == profileOwnerID) { result.put("pendingcount", new ObjectByteIterator(Integer.toString(pendCount).getBytes())); } result.put("resourcecount", new ObjectByteIterator(Integer.toString(resCount).getBytes())); } } 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 listFriends(int requesterID, int profileOwnerID, Set<String> fields, Vector<HashMap<String, ByteIterator>> result, boolean insertImage, boolean testMode) { int retVal = 0; if (requesterID < 0 || profileOwnerID < 0) return -1; // first get all confirmed friendids for profileOwnerID com.mongodb.DB db = null;//from w w w.j av a 2s .c o m try { db = mongo.getDB(database); db.requestStart(); DBCollection collection = db.getCollection("users"); DBObject q = new BasicDBObject().append("_id", profileOwnerID); q.removeField("pic"); BasicDBObject attrs = new BasicDBObject("pic", 0); DBObject queryResult = null; queryResult = collection.findOne(q, attrs); String x = queryResult.get("ConfFriends").toString(); if (!x.equals("")) { x = x.substring(2, x.length() - 1); if (!x.equals("")) { String friendIds[] = x.split(","); BasicDBObject query = new BasicDBObject(); if (!friendListReq) { List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < friendIds.length; i++) { // add to list list.add(Integer.parseInt(friendIds[i].trim())); int cnt = 0; if (i == friendIds.length - 1 || ((i + 1) % 10) == 0) { // query query.put("_id", new BasicDBObject("$in", list)); query.removeField("pic"); // DBCursor cursor = collection.find(query, // fieldsObj); DBCursor cursor = collection.find(query, attrs); 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("ConfFriends"); vals.remove("PendFriends"); 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())); } result.add(vals); } cursor.close(); // empty list list.clear(); } } } else if (friendListReq) {// retrive one list List<Integer> list = new ArrayList<Integer>(); 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, fieldsObj); DBCursor cursor = collection.find(query, attrs); int cnt = 0; while (cursor.hasNext()) { cnt++; 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("ConfFriends"); vals.remove("PendFriends"); vals.remove("wallResurces"); // 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())); } result.add(vals); } cursor.close(); } } } } catch (Exception e) { System.out.println(e.toString()); retVal = -1; } finally { if (db != null) { db.requestDone(); } } return retVal; }