List of usage examples for com.mongodb.client MongoCollection find
FindIterable<TDocument> find(ClientSession clientSession);
From source file:com.imaginea.mongodb.services.impl.DocumentServiceImpl.java
License:Apache License
/** * Deletes a document inside a collection in a database in mongo to which user is connected to. * * @param dbName Name of Database//from w ww .j a v a 2 s . c o m * @param collectionName Name of Collection from which to get all Documents * @param _id Id of Document to be updated * @return Deletion status * @throws DatabaseException throw super type of UndefinedDatabaseException * @throws ValidationException throw super type of * EmptyDatabaseNameException,EmptyCollectionNameException ,EmptyDocumentDataException * @throws CollectionException throw super type of UndefinedCollectionException * @throws DocumentException throw super type of DeleteDocumentException */ public String deleteDocument(String dbName, String collectionName, String _id) throws DatabaseException, CollectionException, DocumentException, ValidationException { if (dbName == null) { throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Database name is null"); } if (dbName.equals("")) { throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Database Name Empty"); } if (collectionName == null) { throw new CollectionException(ErrorCodes.COLLECTION_NAME_EMPTY, "Collection name is null"); } if (collectionName.equals("")) { throw new CollectionException(ErrorCodes.COLLECTION_NAME_EMPTY, "Collection Name Empty"); } String result = null; Document documentData = null; try { // if (!databaseService.getDbList().contains(dbName)) { // throw new DatabaseException(ErrorCodes.DB_DOES_NOT_EXISTS, // "DB [" + dbName + "] DOES NOT EXIST"); // } if (!collectionService.getCollList(dbName).contains(collectionName)) { throw new CollectionException(ErrorCodes.COLLECTION_DOES_NOT_EXIST, "COLLECTION [ " + collectionName + "] _DOES_NOT_EXIST in Db [ " + dbName + "]"); } boolean cappedCollection = (boolean) collectionService.isCappedCollection(dbName, collectionName) .get("capped"); if (cappedCollection) { throw new DocumentException(ErrorCodes.DELETING_FROM_CAPPED_COLLECTION, "Cannot Delete From a Capped Collection"); } if (_id == null) { throw new DocumentException(ErrorCodes.DOCUMENT_EMPTY, "Document is empty"); } Document query = new Document(); ObjectId docId = new ObjectId(_id); query.put("_id", docId); MongoCollection<Document> collection = this.mongoInstance.getDatabase(dbName) .getCollection(collectionName); documentData = collection.find(query).first(); if (documentData == null) { throw new DocumentException(ErrorCodes.DOCUMENT_DOES_NOT_EXIST, "Document does not exist !"); } DeleteResult deleteOne = mongoInstance.getDatabase(dbName).getCollection(collectionName) .deleteOne(query); } catch (MongoException e) { throw new DocumentException(ErrorCodes.DOCUMENT_DELETION_EXCEPTION, e.getMessage()); } result = "Document with Data : [" + documentData + "] has been deleted."; return result; }
From source file:com.inflight.rest.AddFlightService.java
@SuppressWarnings("resource") @POST//from w ww . j a v a 2 s. c o m @Consumes("application/x-www-form-urlencoded") @Produces(MediaType.APPLICATION_JSON) public String signup(@FormParam("username") String username, @FormParam("confirmCode") String confirmCode, @FormParam("fromLocation") String fromLocation, @FormParam("toLocation") String toLocation) throws Exception { MongoClientURI connectionString = new MongoClientURI( "mongodb://ramkrish:1234567@ds029446.mlab.com:29446/inflight"); MongoClient mongoClient = new MongoClient(connectionString); String result = ""; MongoDatabase database = mongoClient.getDatabase("inflight"); MongoCollection<Document> collection = database.getCollection("location"); Document doc = collection.find(or(eq("confirmCode", confirmCode), eq("toLocation", toLocation))).first(); if (doc == null) { Document newDoc = new Document("username", username).append("confirmCode", confirmCode) .append("fromLocation", fromLocation).append("toLocation", toLocation); collection.insertOne(newDoc); result = "{\"success\": true}"; return result; } else { result = "{\"success\": false, \"message\": \"Booking Reference or To Location already exists\"}"; return result; } }
From source file:com.inflight.rest.LoginService.java
@SuppressWarnings("resource") @POST//from www . j a v a 2 s.c o m @Consumes("application/x-www-form-urlencoded") @Produces(MediaType.APPLICATION_JSON) public String login(@FormParam("username") String username, @FormParam("password") String password) throws Exception { MongoClientURI connectionString = new MongoClientURI( "mongodb://ramkrish:1234567@ds029446.mlab.com:29446/inflight"); MongoClient mongoClient = new MongoClient(connectionString); String result = ""; MongoDatabase database = mongoClient.getDatabase("inflight"); MongoCollection<Document> collection = database.getCollection("users"); Document doc = collection.find(eq("username", username)).first(); if (doc != null) { String actualPass = doc.get("password").toString(); if (Password.check(password, actualPass)) { result = "{\"success\": true}"; return result; } else { result = "{\"success\": false, \"message\": \"Invalid Password\"}"; return result; } } else { result = "{\"success\": false, \"message\": \"Invalid Username\"}"; return result; } }
From source file:com.inflight.rest.SignUpService.java
@SuppressWarnings("resource") @POST//from w w w. j a va 2 s. co m @Consumes("application/x-www-form-urlencoded") @Produces(MediaType.APPLICATION_JSON) public String signup(@FormParam("username") String username, @FormParam("password") String password, @FormParam("email") String email) throws Exception { MongoClientURI connectionString = new MongoClientURI( "mongodb://ramkrish:1234567@ds029446.mlab.com:29446/inflight"); MongoClient mongoClient = new MongoClient(connectionString); String result = ""; MongoDatabase database = mongoClient.getDatabase("inflight"); MongoCollection<Document> collection = database.getCollection("users"); Document doc = collection.find(or(eq("username", username), eq("email", email))).first(); if (doc == null) { Document newDoc = new Document("username", username) .append("password", Password.getSaltedHash(password)).append("email", email); collection.insertOne(newDoc); result = "{\"success\": true}"; return result; } else { result = "{\"success\": false, \"message\": \"Username or Email already exists\"}"; return result; } }
From source file:com.jaeksoft.searchlib.crawler.database.DatabaseCrawlMongoDbThread.java
License:Open Source License
@Override public void runner() throws Exception { setStatus(CrawlStatus.STARTING);/* w w w . j a va 2 s. c o m*/ MongoClient mongoClient = null; try { mongoClient = databaseCrawl.getMongoClient(); MongoCollection<Document> collection = databaseCrawl.getCollection(mongoClient); FindIterable<Document> iterable = collection.find(databaseCrawl.getCriteriaObject()); setStatus(CrawlStatus.CRAWL); if (iterable != null) runner_update(iterable); if (updatedIndexDocumentCount > 0 || updatedDeleteDocumentCount > 0) client.reload(); } finally { if (mongoClient != null) mongoClient.close(); } }
From source file:com.left8.evs.utilities.dsretriever.MongoHandler.java
License:Open Source License
/** * This method parses the MongoDB store and returns the tweet that matches * a given ID. <br>//from w ww . j ava 2 s . c o m * <i>Note: Consider creating an index on the field 'id' of the MongoDB Store.</i> * @param id The id of the tweet to be retrieved. * @return A Tweet object containing all the information found in the document * that matched the long 'id'. */ public final Tweet getATweetByIdFromMongoDBStore(long id) { MongoCollection<Document> collection = db.getCollection(config.getRawTweetsCollectionName()); try { FindIterable<Document> iterable = collection.find(new Document(config.getTweetIdFieldName(), id)); Document tweetDoc = iterable.first(); //Get tweet ID long id_ = tweetDoc.getLong(config.getTweetIdFieldName()); Document user = tweetDoc.get(config.getUserDocumentFieldName(), Document.class); //Get the embedded document //User details String username = user.getString(config.getUsernameFieldName()); //Name long userId; try { userId = user.getLong(config.getUserIdFieldName()); } catch (ClassCastException e) { userId = user.getInteger(config.getUserIdFieldName()); } //Tweet text, date and language String text = tweetDoc.getString(config.getTextFieldName()); Date date = tweetDoc.getDate(config.getDateFieldName()); String language = tweetDoc.getString(config.getLanguageFieldName()); //Coordinates Document coordinates = tweetDoc.get(config.getCoordinatesDocumentFieldName(), Document.class); double latitude = -1; double longitude = -1; if (coordinates != null) { try { List<Double> coords = coordinates.get(config.getCoordinatesDocumentFieldName(), ArrayList.class); latitude = coords.get(0); longitude = coords.get(1); } catch (ClassCastException e) { //Case where data where incorrectly casted as integers List<Integer> coords = coordinates.get(config.getCoordinatesDocumentFieldName(), ArrayList.class); latitude = coords.get(0); longitude = coords.get(1); } } //Number of retweets and favorites int numberOfRetweets = tweetDoc.getInteger(config.getRetweetsCountFieldName()); int numberOfFavorites = tweetDoc.getInteger(config.getFavoritesCountFieldName()); boolean isFavorited = tweetDoc.getBoolean(config.getFavoritedFieldName()); boolean isRetweeted = tweetDoc.getBoolean(config.getRetweetedFieldName()); //Retweet status boolean isRetweet; long retweetId; try { Document retweetStatus = tweetDoc.get(config.getRetweetedStatusDocumentFieldName(), Document.class); isRetweet = true; retweetId = retweetStatus.getLong(config.getRetweetIdFieldName()); } catch (NullPointerException e) { isRetweet = false; retweetId = -1; } int stanfordSentiment; try { stanfordSentiment = tweetDoc.getInteger(config.getStanfordSentimentName()); } catch (NullPointerException e) { stanfordSentiment = -1; } int naiveBayesSentiment; try { naiveBayesSentiment = tweetDoc.getInteger(config.getNaiveBayesSentimentName()); } catch (NullPointerException e) { naiveBayesSentiment = -10; } int bayesianNetSentiment; try { bayesianNetSentiment = tweetDoc.getInteger(config.getBayesianNetSentimentName()); } catch (NullPointerException e) { bayesianNetSentiment = -10; } int posEmot, negEmot; try { posEmot = tweetDoc.getInteger(config.getPositiveEmoticonFieldName()); negEmot = tweetDoc.getInteger(config.getNegativeEmoticonFieldName()); } catch (NullPointerException e) { posEmot = 0; negEmot = 0; } Tweet tweet = new Tweet(id_, username, userId, text, date, latitude, longitude, numberOfRetweets, numberOfFavorites, isRetweet, isFavorited, isRetweeted, language, retweetId, stanfordSentiment, posEmot, negEmot, naiveBayesSentiment, bayesianNetSentiment); return tweet; } catch (MongoException e) { Utilities.printMessageln("Unknown Mongo problem with tweet '" + id + "'."); Logger.getLogger(MongoHandler.class.getName()).log(Level.SEVERE, null, e); return null; } catch (NullPointerException e) { //Tweet does not exist return null; } }
From source file:com.left8.evs.utilities.dsretriever.MongoHandler.java
License:Open Source License
/** * Determines whether a tweet exists in the MongoDB Store. * @param id The id of the tweet to be searched. * @return True if the tweet exists, false otherwise. *//* w ww.ja v a2 s . co m*/ public final boolean tweetExists(long id) { MongoCollection<Document> collection = db.getCollection(config.getRawTweetsCollectionName()); try { collection.find(new Document(config.getTweetIdFieldName(), id)); return true; } catch (NullPointerException e) { //Tweet does not exist return false; } }
From source file:com.left8.evs.utilities.dsretriever.MongoHandler.java
License:Open Source License
/** * Checks whether a tweet is already annotated with its stanfordSentiment. * @param id The ID of the tweet to be checked for. * @param fieldName The MongoDB field name of ID. * @return True if the tweet is stanfordSentiment annotated, false otherwise. *//*from w w w .j ava 2 s .c o m*/ public final boolean tweetHasSentiment(long id, String fieldName) { MongoCollection<Document> collection = db.getCollection(config.getRawTweetsCollectionName()); int sentiment; FindIterable<Document> iterable = collection.find(new Document(config.getTweetIdFieldName(), id)); Document tweetDoc = iterable.first(); try { sentiment = tweetDoc.getInteger(fieldName); return true; } catch (NullPointerException e) { //Tweet does not exist return false; } }
From source file:com.my.food.recipe.db.MongoDb.java
public RecipeSummary getRecipeSummary(String recipeId) { MongoCollection<BsonDocument> collectionRecipeSummary = database.getCollection("recipeSummary", BsonDocument.class); BsonDocument document = collectionRecipeSummary.find(eq("_id", recipeId)).first(); if (document != null) { LOG.info("get document = {}", document.toString()); return new RecipeSummary().fromJson(document.toJson()); } else {//from w ww . java 2 s . c om LOG.info("Null Document for recipeId={}", recipeId); return null; } }
From source file:com.redhat.thermostat.gateway.service.jvms.mongo.JvmInfoMongoStorageHandler.java
License:Open Source License
public String getJvmsTree(MongoCollection<Document> collection, boolean aliveOnly, String excludes, String includes, int limit, int offset) { FindIterable<Document> documents; if (aliveOnly) { documents = collection.find(lt(StorageFields.STOP_TIME, 0)); } else {//from w ww .j a v a 2s.co m documents = collection.find(); } documents = documents.limit(limit).skip(offset); boolean includeSystemId = true; if (excludes != null) { List<String> excludesList = new ArrayList<>(Arrays.asList(excludes.split(","))); if (excludesList.contains(StorageFields.SYSTEM_ID)) { excludesList.remove(StorageFields.SYSTEM_ID); includeSystemId = false; } if (excludesList.size() > 0) { documents = documents.projection(fields(exclude(excludesList), excludeId())); } else { documents = documents.projection(excludeId()); } } else if (includes != null) { List<String> includesList = new ArrayList<>(Arrays.asList(includes.split(","))); if (!includesList.contains(StorageFields.SYSTEM_ID)) { includesList.add(StorageFields.SYSTEM_ID); includeSystemId = false; } documents = documents.projection(fields(include(includesList), excludeId())); } else { documents = documents.projection(excludeId()); } final Map<String, StringBuilder> map = new HashMap<>(); final boolean finalIncludeSystemId = includeSystemId; documents.forEach(new Block<Document>() { @Override public void apply(Document document) { String systemId = document.getString(StorageFields.SYSTEM_ID); if (!finalIncludeSystemId) { document.remove(StorageFields.SYSTEM_ID); } if (!map.containsKey(systemId)) { map.put(systemId, new StringBuilder().append("{\"" + StorageFields.SYSTEM_ID + "\":\"" + systemId + "\", \"" + StorageFields.JVMS + "\":[")); } map.get(systemId).append(document.toJson()).append(","); } }); StringBuilder responseBuilder = new StringBuilder().append("{ \"" + StorageFields.RESPONSE + "\" : ["); if (map.size() > 0) { for (StringBuilder systemBuilder : map.values()) { responseBuilder.append(systemBuilder.deleteCharAt(systemBuilder.length() - 1).toString()); responseBuilder.append("]},"); } responseBuilder.deleteCharAt(responseBuilder.length() - 1); } responseBuilder.append("]}"); return responseBuilder.toString(); }