Example usage for com.mongodb.client MongoCollection find

List of usage examples for com.mongodb.client MongoCollection find

Introduction

In this page you can find the example usage for com.mongodb.client MongoCollection find.

Prototype

FindIterable<TDocument> find();

Source Link

Document

Finds all documents in the collection.

Usage

From source file:com.company.Action.java

License:Apache License

public void run() throws NotFound, ResponseException, InterruptedException {
    Way2SMS way2SMS = new Way2SMS();
    way2SMS.Login(USERNAME, PASSWORD);//from   w  w  w. ja v  a2 s  . c o m

    Set<User> hashset = new HashSet<>();
    Set<String> numbers = new HashSet<>();
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    MongoDatabase database = mongoClient.getDatabase("Users");
    MongoCollection<Document> collection = database.getCollection("credenzappusers");
    //        System.out.println(collection.count());
    for (Document cur : collection.find()) {
        if (cur.get("Phone1") != null) {
            String value = String.valueOf(cur.get("Phone1"));
            if (value.length() == 10) {
                //                    System.out.println(value);
                if (!numbers.contains(value)) {
                    numbers.add(value);
                    hashset.add(new User(((String) cur.get("Name1")).split(" ")[0], value));
                }
            }
        }
        if (cur.get("Phone2") != null) {
            String value = String.valueOf(cur.get("Phone2"));
            if (value.length() == 10) {
                //                    System.out.println(value);
                if (!numbers.contains(value)) {
                    numbers.add(value);
                    hashset.add(new User(((String) cur.get("Name2")).split(" ")[0], value));
                }
            }
        }
        if (cur.get("Phone3") != null) {
            String value = String.valueOf(cur.get("Phone3"));
            if (value.length() == 10) {
                //                    System.out.println(value);
                if (!numbers.contains(value)) {
                    numbers.add(value);
                    hashset.add(new User(((String) cur.get("Name3")).split(" ")[0], value));
                }
            }
        }
        //            System.out.println("Phone2 is"+cur.get("Phone2"));
    }

    System.out.println(hashset.size());

    collection = database.getCollection("credenzreceipt");
    System.out.println(collection.count());
    for (Document cur : collection.find()) {
        if (cur.get("Contact1") != null) {
            String value = String.valueOf(cur.get("Contact1"));
            if (value.length() == 10) {
                //                    System.out.println(value);
                if (!numbers.contains(value)) {
                    numbers.add(value);
                    hashset.add(new User(((String) cur.get("Name1")).split(" ")[0], value));
                }
            }
        }
        if (cur.get("Contact2") != null) {
            String value = String.valueOf(cur.get("Contact2"));
            if (value.length() == 10) {
                //                    System.out.println(value);
                if (!numbers.contains(value)) {
                    numbers.add(value);
                    hashset.add(new User(((String) cur.get("Name2")).split(" ")[0], value));
                }
            }
        }
        if (cur.get("Contact3") != null) {
            String value = String.valueOf(cur.get("Contact3"));
            if (value.length() == 10) {
                //                    System.out.println(value);
                if (!numbers.contains(value)) {
                    numbers.add(value);
                    try {
                        hashset.add(new User(((String) cur.get("Name3")).split(" ")[0], value));
                    } catch (Exception e) {
                        System.out.println("cought exception");
                    }
                }
            }
        }
        //            System.out.println("Phone2 is"+cur.get("Phone2"));
    }

    collection = database.getCollection("droidfest_users");
    //        System.out.println(collection.count());
    for (Document cur : collection.find()) {
        if (cur.get("phone_no") != null) {
            String value = String.valueOf(cur.get("phone_no"));
            if (value.length() == 10) {
                //                    System.out.println(value);
                if (!numbers.contains(value)) {
                    numbers.add(value);
                    hashset.add(new User(((String) cur.get("name")).split(" ")[0], value));
                }
            }
        }
    }

    collection = database.getCollection("hingemeetusers");
    //        System.out.println(collection.count());
    for (Document cur : collection.find()) {
        if (cur.get("Number") != null) {
            String value = String.valueOf(cur.get("Number"));
            if (value.length() == 10) {
                //                    System.out.println(value);
                if (!numbers.contains(value)) {
                    numbers.add(value);
                    hashset.add(new User(((String) cur.get("Name")).split(" ")[0], value));
                }
            }
        }
    }

    System.out.println(hashset.size());
    int i = 1;
    for (User user : hashset) {
        //            System.out.print(user.getName());
        //            System.out.println(user.getPhone_no());
        i++;
        if (i > 7) {
            way2SMS.SendSMS(user.getPhone_no(), "Hi " + user.getName()
                    + "! This is how you can build your Campus Startup: http://bit.ly/28Pa8aC FREE first lesson: http://bit.ly/28POhxJ Only for you:)");
            Thread.sleep(4000);
        } else {
            System.out.println("Interrupted for " + user.getPhone_no());
        }
        System.out.println(i);
    }
    //        List <User> number=new ArrayList<>();
    //        number.add(new User("lol","9819124829"));
    //        number.add(new User("lol","8446499908"));
    //        number.add(new User("lol","7709758284"));
    //        number.add(new User("lol","8956613425"));
    //        number.add(new User("lol","7276807536"));
    //        for (int i=0;i<number.size();i++) {
    //            way2SMS.SendSMS(number.get(i).getPhone_no(), "Hi "+number.get(i).getName()+"! This is how you can build your Campus Startup: http://bit.ly/28Pa8aC FREE first lesson: http://bit.ly/28POhxJ Only for you :)"); //args ; Phone no , Message
    //        }
}

From source file:com.gs.obevo.mongodb.impl.MongoDbChangeAuditDao.java

License:Apache License

@Override
public ImmutableList<Change> getDeployedChanges() {
    return env.getPhysicalSchemas().flatCollect(new Function<PhysicalSchema, Iterable<Change>>() {
        @Override//from   w  w w .j a  v a  2  s . c o m
        public Iterable<Change> valueOf(PhysicalSchema physicalSchema) {
            MongoDatabase database = mongoClient.getDatabase(physicalSchema.getPhysicalName());
            MongoCollection<Document> auditCollection = database.getCollection(getAuditContainerName());

            MutableList<Change> changes = iterableToCollection(auditCollection.find())
                    .collect(new Function<Document, Change>() {
                        @Override
                        public Change valueOf(Document doc) {
                            String artfType = doc.getString("ARTFTYPE");
                            Change artf;
                            if (artfType.equals("I")) {
                                artf = new ChangeIncremental();
                            } else if (artfType.equals("R")) {
                                artf = new ChangeRerunnable();
                            } else {
                                throw new IllegalArgumentException("This type does not exist " + artfType);
                            }

                            artf.setChangeKey(
                                    new ChangeKey(InternMap.instance().intern(doc.getString("DBSCHEMA")),
                                            platform.getChangeType(doc.getString("CHANGETYPE")),
                                            InternMap.instance().intern(doc.getString("OBJECTNAME")),
                                            doc.getString(changeNameColumn)));

                            artf.setActive(doc.getInteger("ACTIVE") == 1);
                            artf.setContentHash(doc.getString("CONTENTHASH"));
                            artf.setTimeInserted(new Timestamp(doc.getDate(timeInsertedColumn).getTime()));
                            artf.setTimeUpdated(new Timestamp(doc.getDate(timeUpdatedColumn).getTime()));

                            artf.setRollbackContent(doc.getString(rollbackContentColumn));

                            return artf;
                        }
                    });

            return changes.toImmutable();
        }
    }).toList().toImmutable();
}

From source file:com.gs.obevo.mongodb.impl.MongoDbDeployExecutionDao.java

License:Apache License

@Override
public ImmutableCollection<DeployExecution> getDeployExecutions(String schema) {
    PhysicalSchema physicalSchema = env.getPhysicalSchema(schema);

    MongoDatabase database = mongoClient.getDatabase(physicalSchema.getPhysicalName());
    MongoCollection<Document> auditCollection = database.getCollection(deployExecutionTableName);

    return iterableToCollection(auditCollection.find()).collect(new Function<Document, DeployExecution>() {
        @Override//from w w  w .j  a v a  2 s. c  om
        public DeployExecution valueOf(Document doc) {
            MutableList<Document> attrsList = ListAdapter.adapt(doc.get("attrs", List.class));
            MutableList<DeployExecutionAttribute> attrs = attrsList
                    .collect(new Function<Document, DeployExecutionAttribute>() {
                        @Override
                        public DeployExecutionAttribute valueOf(Document object) {
                            return new DeployExecutionAttributeImpl(object.getString(attrNameColName),
                                    object.getString(attrValueColName));
                        }
                    });

            DeployExecutionImpl exec = new DeployExecutionImpl(doc.getString(requesterIdColName),
                    doc.getString(deployExecutionIdColName), doc.getString(dbSchemaColName),
                    doc.getString(toolVersionColName), new Timestamp(doc.getDate(deployTimeColName).getTime()),
                    doc.getBoolean(initCommandColName), doc.getBoolean(rollbackCommandColName),
                    doc.getString(productVersionColName), doc.getString(reasonColName),
                    attrs.toSet().toImmutable());
            exec.setId(doc.getLong(idColName));

            return exec;
        }
    }).toImmutable();
}

From source file:com.imaginea.mongodb.services.impl.CollectionServiceImpl.java

License:Apache License

/**
 * Deletes a collection inside a database in mongo to which user is connected to.
 *
 * @param dbName Name of Database in which to insert a collection
 * @param collectionName Name of Collection to be inserted
 * @return Success if deletion is successful else throw exception
 * @throws DatabaseException throw super type of UndefinedDatabaseException
 * @throws ValidationException throw super type of
 *         EmptyDatabaseNameException,EmptyCollectionNameException
 * @throws CollectionException throw super type of
 *         UndefinedCollectionException,DeleteCollectionException
 *///from ww  w. ja v  a 2  s. co  m

private void createCollection(CreateCollectionOptions options, MongoCollection<Document> selectedCollection,
        String selectedCollectionName, MongoDatabase db) {
    db.createCollection(selectedCollectionName + "_temp", options);
    MongoCollection<Document> tempCollection = db.getCollection(selectedCollectionName + "_temp");

    MongoCursor<Document> cur = selectedCollection.find().iterator();
    while (cur.hasNext()) {
        Document obj = cur.next();
        tempCollection.insertOne(obj);
    }
    MongoNamespace namespace = selectedCollection.getNamespace();
    selectedCollection.drop();
    tempCollection.renameCollection(namespace);
}

From source file:com.imos.sample.SampleMongoDB.java

public static void main(String[] args) {
    MongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017");
    MongoClient mongoClient = new MongoClient(connectionString);
    MongoDatabase database = mongoClient.getDatabase("sampledb");
    MongoCollection<Document> collection = database.getCollection("sampleLog");
    System.out.println(collection.count());
    MongoCursor<Document> cursor = collection.find().iterator();
    ObjectMapper mapper = new ObjectMapper();
    try {//from w w  w. ja v a 2 s.co m
        while (cursor.hasNext()) {
            try {
                System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(cursor.next()));
            } catch (JsonProcessingException ex) {
                Logger.getLogger(SampleMongoDB.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    } finally {
        cursor.close();
    }
}

From source file:com.imos.sample.SampleMongoDB.java

private static void sampleOne(MongoDatabase database) throws JsonProcessingException {
    MongoCollection<Document> collection = database.getCollection("test");
    Document doc = new Document("name", "MongoDB").append("type", "database").append("count", 1)
            .append("versions", Arrays.asList("v3.2", "v3.0", "v2.6"))
            .append("info", new Document("x", 203).append("y", 102));
    //        collection.insertOne(doc);
    System.out.println(collection.count());
    MongoCursor<Document> cursor = collection.find().iterator();
    ObjectMapper mapper = new ObjectMapper();
    //        try {
    //            while (cursor.hasNext()) {
    ////                System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(cursor.next()));
    //            }
    //        } finally {
    //            cursor.close();
    //        }/*from   ww w . java 2  s  .c  om*/

    Document myDoc = collection.find(eq("type", "database")).first();
    System.out.println(myDoc.toJson());
}

From source file:com.inflight.rest.ViewPlaces.java

@SuppressWarnings("resource")
@GET/*from   w  ww  . java2s  . co m*/
@Path("/all")
@Produces(MediaType.APPLICATION_JSON)
public String getLocations() {

    JSONArray jsonArr = new JSONArray();

    MongoClientURI connectionString = new MongoClientURI(
            "mongodb://ramkrish:1234567@ds029446.mlab.com:29446/inflight");
    MongoClient mongoClient = new MongoClient(connectionString);

    MongoDatabase database = mongoClient.getDatabase("inflight");

    MongoCollection<Document> collection = database.getCollection("location");

    MongoCursor<Document> cursor = collection.find().iterator();
    try {
        while (cursor.hasNext()) {
            jsonArr.put(cursor.next());

        }
    } finally {
        cursor.close();
    }

    return jsonArr.toString();
}

From source file:com.kurniakue.data.Record.java

public static <T extends Record> List<T> loadList(T dummy, Document filter, Document sort) {
    List<T> list = new ArrayList<>();
    Class<T> clazz = (Class<T>) dummy.getClass();

    MongoCollection collection = dummy.getCollection();
    FindIterable<Document> result;
    if (filter == null) {
        result = collection.find();
    } else {/*  w w w.j a  v  a2  s . c om*/
        result = collection.find(filter);
    }

    if (sort != null) {
        result = result.sort(sort);
    }

    for (MongoCursor<Document> iterator = result.iterator(); iterator.hasNext();) {
        Document document = iterator.next();
        T record = Tool.neo(clazz);
        record.putAll(document);
        list.add(record);
    }

    return list;
}

From source file:com.left8.evs.utilities.dsretriever.MongoHandler.java

License:Open Source License

/**
 * Retrieves all stored retrievedTweets in MongoDB Store.
 * @return A List containing all retrieved retrievedTweets
 *//*from   w w w .  j a  va  2  s.c o m*/
public final List<Tweet> retrieveAllTweetsFiltered() {
    List<Tweet> retrievedTweets = new ArrayList<>();
    if (langFilter.equals("no_filter")) {
        Utilities.printMessageln("No language filter was applied. Retrieving " + "all tweets, unfiltered.");
    }

    MongoCollection<Document> collection = db.getCollection(config.getRawTweetsCollectionName());

    try {
        FindIterable<Document> iterable = collection.find(); //Load all documents
        iterable.forEach(new Block<Document>() {
            @Override
            public void apply(final Document tweetDoc) {
                if (langFilter.equals("no_filter")
                        || tweetDoc.getString(config.getLanguageFieldName()).equals(langFilter)) {
                    //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; //User ID
                    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());
                    long retweetId;

                    //Retweet status
                    boolean isRetweet;
                    try {
                        Document retweetStatus = tweetDoc.get(config.getRetweetedStatusDocumentFieldName(),
                                Document.class);
                        isRetweet = true;
                        try {
                            retweetId = retweetStatus.getLong(config.getRetweetIdFieldName());
                        } catch (ClassCastException e) {
                            retweetId = retweetStatus.getInteger(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);

                    retrievedTweets.add(tweet);
                }
            }
        });
        return retrievedTweets;
    } catch (MongoException e) {
        Utilities.printMessageln("Cannot find documents in MongoDB Store.");
        Logger.getLogger(MongoHandler.class.getName()).log(Level.SEVERE, null, e);
        return null;
    }
}

From source file:com.mycompany.citysearchnosql.Executioner.java

public static void main(final String[] args) {

    // 1. Connect to MongoDB instance running on localhost
    MongoClient mongoClient = new MongoClient();

    // Access database named 'test'
    MongoDatabase database = mongoClient.getDatabase("test");

    // Access collection named 'restaurants'
    MongoCollection<Document> collection = database.getCollection("restaurants");

    // 2. Insert 
    List<Document> documents = asList(
            new Document("name", "Sun Bakery Trattoria").append("stars", 4).append("categories",
                    asList("Pizza", "Pasta", "Italian", "Coffee", "Sandwiches")),
            new Document("name", "Blue Bagels Grill").append("stars", 3).append("categories",
                    asList("Bagels", "Cookies", "Sandwiches")),
            new Document("name", "Hot Bakery Cafe").append("stars", 4).append("categories",
                    asList("Bakery", "Cafe", "Coffee", "Dessert")),
            new Document("name", "XYZ Coffee Bar").append("stars", 5).append("categories",
                    asList("Coffee", "Cafe", "Bakery", "Chocolates")),
            new Document("name", "456 Cookies Shop").append("stars", 4).append("categories",
                    asList("Bakery", "Cookies", "Cake", "Coffee")));

    collection.insertMany(documents);// w  w  w. j  a v a 2  s. c o m

    // 3. Query 
    List<Document> results = collection.find().into(new ArrayList<>());

    // 4. Create Index 
    collection.createIndex(Indexes.ascending("name"));
    // 5. Perform Aggregation
    collection.aggregate(asList(match(eq("categories", "Bakery")), group("$stars", sum("count", 1))));

    mongoClient.close();
}