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(ClientSession clientSession);

Source Link

Document

Finds all documents in the collection.

Usage

From source file:mongotwitter.MongoTwitter.java

public void follow(String followed) {
    if (followed.equals(nick)) {
        System.out.println("* Follow failed : You cannot follow yourself");
    } else {/*from   ww  w  .ja v a  2  s . c  o  m*/
        MongoCollection<Document> users = db.getCollection("users");
        Document oldDoc = users.find(eq("username", followed)).first();
        if (oldDoc == null) {
            System.out.println("* Follow failed : Username does not exist");
        } else {
            MongoCollection<Document> friends = db.getCollection("friends");
            Document frDoc = friends.find(and(eq("username", nick), eq("friend", followed))).first();
            if (frDoc != null) {
                System.out.println("* Follow failed : You already followed @" + followed);
            } else {
                MongoCollection<Document> followers = db.getCollection("followers");
                Date ts = new Date();
                Document friendDoc = new Document("username", nick).append("friend", followed).append("since",
                        ts);
                Document followerDoc = new Document("username", followed).append("follower", nick)
                        .append("since", ts);
                friends.insertOne(friendDoc);
                followers.insertOne(followerDoc);
                System.out.println("* You successfully followed " + followed);
            }
        }
    }
}

From source file:mongotwitter.MongoTwitter.java

public void tweet(String body) {
    final ObjectId tweet_id = new ObjectId();
    final Date time = new Date();
    MongoCollection<Document> tweets = db.getCollection("tweets");
    MongoCollection<Document> userline = db.getCollection("userline");
    MongoCollection<Document> timeline = db.getCollection("timeline");
    MongoCollection<Document> followers = db.getCollection("followers");

    Document tweetDoc = new Document("tweet_id", tweet_id).append("username", nick).append("body", body);

    Document userDoc = new Document("username", nick).append("time", time).append("tweet_id", tweet_id);

    List<Document> timelineList = new ArrayList<>();
    List<Document> followerList = followers.find(eq("username", nick)).into(new ArrayList<Document>());
    for (Document doc : followerList) {
        String follower = (String) doc.get("follower");
        Document timeDoc = new Document("username", follower).append("time", time).append("tweet_id", tweet_id);
        timelineList.add(timeDoc);//w w  w .j a v  a2  s.  co m
    }

    tweets.insertOne(tweetDoc);
    userline.insertOne(userDoc);
    timeline.insertMany(timelineList);

    System.out.println("* You tweeted \"" + body + "\" at " + time);
}

From source file:mongotwitter.MongoTwitter.java

public void showUserline(String username) {
    MongoCollection<Document> users = db.getCollection("users");
    Document oldDoc = users.find(eq("username", username)).first();
    if (oldDoc == null) {
        System.out.println("* Show userline failed : Username does not exist");
    } else {/*from w  w w.j  a  v  a2  s.c o m*/
        MongoCollection<Document> userline = db.getCollection("userline");
        List<Document> userlineList = userline.find(eq("username", username)).into(new ArrayList<Document>());
        if (userlineList.isEmpty()) {
            System.out.println("* " + username + "'s userline is empty");
        } else {
            MongoCollection<Document> tweets = db.getCollection("tweets");
            List<Date> timeList = new ArrayList<>();
            List<String> bodyList = new ArrayList<>();
            for (Document doc : userlineList) {
                Date time = (Date) doc.get("time");
                ObjectId tweet_id = (ObjectId) doc.get("tweet_id");
                Document tweetDoc = tweets.find(eq("tweet_id", tweet_id)).first();
                String body = (String) tweetDoc.get("body");

                timeList.add(time);
                bodyList.add(body);
            }

            System.out.println("* @" + username + "'s userline");
            for (int i = 0; i < timeList.size(); i++) {
                System.out.println("[" + timeList.get(i) + "] " + bodyList.get(i));
            }
        }
    }
}

From source file:mongotwitter.MongoTwitter.java

public void showTimeline(String username) {
    MongoCollection<Document> users = db.getCollection("users");
    Document oldDoc = users.find(eq("username", username)).first();
    if (oldDoc == null) {
        System.out.println("* Show timeline failed : Username does not exist");
    } else {/*from   w  ww. j a v  a 2 s  .co m*/
        MongoCollection<Document> timeline = db.getCollection("timeline");
        List<Document> timelineList = timeline.find(eq("username", username)).into(new ArrayList<Document>());
        if (timelineList.isEmpty()) {
            System.out.println("* @" + username + "'s timeline is empty");
        } else {
            MongoCollection<Document> tweets = db.getCollection("tweets");
            List<Date> timeList = new ArrayList<Date>();
            List<String> nameList = new ArrayList<String>();
            List<String> bodyList = new ArrayList<String>();
            for (Document doc : timelineList) {
                Date time = (Date) doc.get("time");
                ObjectId tweet_id = (ObjectId) doc.get("tweet_id");
                Document tweetDoc = tweets.find(eq("tweet_id", tweet_id)).first();
                String name = (String) tweetDoc.get("username");
                String body = (String) tweetDoc.get("body");

                timeList.add(time);
                nameList.add(name);
                bodyList.add(body);
            }

            System.out.println("* @" + username + "'s timeline");
            for (int i = 0; i < timeList.size(); i++) {
                System.out.println("[" + timeList.get(i) + "] @" + nameList.get(i) + " : " + bodyList.get(i));
            }
        }
    }
}

From source file:net.modelbased.proasense.storage.reader.EventReaderMongoSync.java

License:Apache License

public List<Document> call() {
    // Connect to MongoDB database
    MongoClient mongoClient = new MongoClient(new MongoClientURI(this.mongoURL));
    MongoDatabase database = mongoClient.getDatabase(this.database);

    MongoCollection<Document> collection = database.getCollection(this.collectionId);

    // Create document list for query result
    List<Document> foundDocuments = new ArrayList<Document>();

    if (queryType.equals(EventQueryType.SIMPLE) && queryOperation.equals(EventQueryOperation.DEFAULT)) {
        FindIterable<Document> it = collection
                .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime)));

        MongoCursor<Document> cursor = it.iterator();
        while (cursor.hasNext()) {
            Document doc = cursor.next();
            foundDocuments.add(doc);/*from ww w.j a  va  2 s .c  o m*/
        }
    }

    if (queryType.equals(EventQueryType.SIMPLE) && queryOperation.equals(EventQueryOperation.AVERAGE)) {
        FindIterable<Document> it = collection
                .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime)));

        boolean longProperty = false;
        boolean doubleProperty = false;
        MongoCursor<Document> firstCursor = it.iterator();
        if (firstCursor.hasNext()) {
            Document doc = firstCursor.next();
            Document eventProps = (Document) doc.get("eventProperties");
            Object valueObj = eventProps.get(this.propertyKey);
            if (valueObj instanceof Long)
                longProperty = true;
            else if (valueObj instanceof Double)
                doubleProperty = true;
        }

        long resultAverageLong = 0;
        double resultAverageDouble = 0;
        long collectionSize = 0;
        MongoCursor<Document> cursor = it.iterator();
        while (cursor.hasNext()) {
            collectionSize++;
            Document doc = cursor.next();
            Document eventProps = (Document) doc.get("eventProperties");
            if (longProperty) {
                Long value = (Long) eventProps.get(this.propertyKey);
                resultAverageLong = resultAverageLong + value;
            } else if (doubleProperty) {
                Double value = (Double) eventProps.get(this.propertyKey);
                resultAverageDouble = resultAverageDouble + value;
                doubleProperty = true;
            }
        }

        if (longProperty) {
            Long resultAverage = resultAverageLong / collectionSize;
            Document resultDoc = new Document("RESULT", resultAverage);
            foundDocuments.add(resultDoc);
        } else if (doubleProperty) {
            Double resultAverage = resultAverageDouble / collectionSize;
            Document resultDoc = new Document("RESULT", resultAverage);
            foundDocuments.add(resultDoc);
        }
    }

    if (queryType.equals(EventQueryType.SIMPLE) && queryOperation.equals(EventQueryOperation.MAXIMUM)) {
        FindIterable<Document> it = collection
                .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime)));

        boolean longProperty = false;
        boolean doubleProperty = false;
        MongoCursor<Document> firstCursor = it.iterator();
        if (firstCursor.hasNext()) {
            Document doc = firstCursor.next();
            Document eventProps = (Document) doc.get("eventProperties");
            Object valueObj = eventProps.get(this.propertyKey);
            if (valueObj instanceof Long)
                longProperty = true;
            else if (valueObj instanceof Double)
                doubleProperty = true;
        }

        long resultMaximumLong = Long.MIN_VALUE;
        double resultMaximumDouble = Double.MIN_VALUE;
        MongoCursor<Document> cursor = it.iterator();
        while (cursor.hasNext()) {
            Document doc = cursor.next();
            Document eventProps = (Document) doc.get("eventProperties");
            if (longProperty) {
                long value = (Long) eventProps.get(this.propertyKey);
                if (value > resultMaximumLong)
                    resultMaximumLong = value;
            } else if (doubleProperty) {
                double value = (Double) eventProps.get(this.propertyKey);
                if (value > resultMaximumDouble)
                    resultMaximumDouble = value;
            }
        }

        if (longProperty) {
            Long resultMaximum = resultMaximumLong;
            Document resultDoc = new Document("RESULT", resultMaximum);
            foundDocuments.add(resultDoc);
        } else if (doubleProperty) {
            Double resultMaximum = resultMaximumDouble;
            Document resultDoc = new Document("RESULT", resultMaximum);
            foundDocuments.add(resultDoc);
        }
    }

    if (queryType.equals(EventQueryType.SIMPLE) && queryOperation.equals(EventQueryOperation.MINUMUM)) {
        FindIterable<Document> it = collection
                .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime)));

        boolean longProperty = false;
        boolean doubleProperty = false;
        MongoCursor<Document> firstCursor = it.iterator();
        if (firstCursor.hasNext()) {
            Document doc = firstCursor.next();
            Document eventProps = (Document) doc.get("eventProperties");
            Object valueObj = eventProps.get(this.propertyKey);
            if (valueObj instanceof Long)
                longProperty = true;
            else if (valueObj instanceof Double)
                doubleProperty = true;
        }

        long resultMinimumLong = Long.MAX_VALUE;
        double resultMinimumDouble = Double.MAX_VALUE;
        MongoCursor<Document> cursor = it.iterator();
        while (cursor.hasNext()) {
            Document doc = cursor.next();
            Document eventProps = (Document) doc.get("eventProperties");
            if (longProperty) {
                long value = (Long) eventProps.get(this.propertyKey);
                if (value < resultMinimumLong)
                    resultMinimumLong = value;
            } else if (doubleProperty) {
                Double value = (Double) eventProps.get(this.propertyKey);
                if (value < resultMinimumDouble)
                    resultMinimumDouble = value;
            }
        }

        if (longProperty) {
            long resultMinimum = resultMinimumLong;
            Document resultDoc = new Document("RESULT", resultMinimum);
            foundDocuments.add(resultDoc);
        } else if (doubleProperty) {
            double resultMinimum = resultMinimumDouble;
            Document resultDoc = new Document("RESULT", resultMinimum);
            foundDocuments.add(resultDoc);
        }
    }

    if (queryType.equals(EventQueryType.DERIVED) && queryOperation.equals(EventQueryOperation.DEFAULT)) {
        FindIterable<Document> it = collection
                .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime)));

        MongoCursor<Document> cursor = it.iterator();
        while (cursor.hasNext()) {
            Document doc = cursor.next();
            foundDocuments.add(doc);
        }
    }

    if (queryType.equals(EventQueryType.DERIVED) && queryOperation.equals(EventQueryOperation.AVERAGE)) {
        FindIterable<Document> it = collection
                .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime)));

        boolean longProperty = false;
        boolean doubleProperty = false;
        MongoCursor<Document> firstCursor = it.iterator();
        if (firstCursor.hasNext()) {
            Document doc = firstCursor.next();
            Document eventProps = (Document) doc.get("eventProperties");
            Object valueObj = eventProps.get(this.propertyKey);
            if (valueObj instanceof Long)
                longProperty = true;
            else if (valueObj instanceof Double)
                doubleProperty = true;
        }

        long resultAverageLong = 0;
        double resultAverageDouble = 0;
        long collectionSize = 0;
        MongoCursor<Document> cursor = it.iterator();
        while (cursor.hasNext()) {
            collectionSize++;
            Document doc = cursor.next();
            Document eventProps = (Document) doc.get("eventProperties");
            if (longProperty) {
                Long value = (Long) eventProps.get(this.propertyKey);
                resultAverageLong = resultAverageLong + value;
            } else if (doubleProperty) {
                Double value = (Double) eventProps.get(this.propertyKey);
                resultAverageDouble = resultAverageDouble + value;
            }
        }

        if (longProperty) {
            Long resultAverage = resultAverageLong / collectionSize;
            Document resultDoc = new Document("RESULT", resultAverage);
            foundDocuments.add(resultDoc);
        } else if (doubleProperty) {
            Double resultAverage = resultAverageDouble / collectionSize;
            Document resultDoc = new Document("RESULT", resultAverage);
            foundDocuments.add(resultDoc);
        }
    }

    if (queryType.equals(EventQueryType.DERIVED) && queryOperation.equals(EventQueryOperation.MAXIMUM)) {
        FindIterable<Document> it = collection
                .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime)));

        boolean longProperty = false;
        boolean doubleProperty = false;
        MongoCursor<Document> firstCursor = it.iterator();
        if (firstCursor.hasNext()) {
            Document doc = firstCursor.next();
            Document eventProps = (Document) doc.get("eventProperties");
            Object valueObj = eventProps.get(this.propertyKey);
            if (valueObj instanceof Long)
                longProperty = true;
            else if (valueObj instanceof Double)
                doubleProperty = true;
        }

        long resultMaximumLong = Long.MIN_VALUE;
        double resultMaximumDouble = Double.MIN_VALUE;
        MongoCursor<Document> cursor = it.iterator();
        while (cursor.hasNext()) {
            Document doc = cursor.next();
            Document eventProps = (Document) doc.get("eventProperties");
            if (longProperty) {
                long value = (Long) eventProps.get(this.propertyKey);
                if (value > resultMaximumLong)
                    resultMaximumLong = value;
            } else if (doubleProperty) {
                double value = (Double) eventProps.get(this.propertyKey);
                if (value > resultMaximumDouble)
                    resultMaximumDouble = value;
                doubleProperty = true;
            }
        }

        if (longProperty) {
            long resultMaximum = resultMaximumLong;
            Document resultDoc = new Document("RESULT", resultMaximum);
            foundDocuments.add(resultDoc);
        } else if (doubleProperty) {
            double resultMaximum = resultMaximumDouble;
            Document resultDoc = new Document("RESULT", resultMaximum);
            foundDocuments.add(resultDoc);
        }
    }

    if (queryType.equals(EventQueryType.DERIVED) && queryOperation.equals(EventQueryOperation.MINUMUM)) {
        FindIterable<Document> it = collection
                .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime)));

        boolean longProperty = false;
        boolean doubleProperty = false;
        MongoCursor<Document> firstCursor = it.iterator();
        if (firstCursor.hasNext()) {
            Document doc = firstCursor.next();
            Document eventProps = (Document) doc.get("eventProperties");
            Object valueObj = eventProps.get(this.propertyKey);
            if (valueObj instanceof Long)
                longProperty = true;
            else if (valueObj instanceof Double)
                doubleProperty = true;
        }

        long resultMinimumLong = Long.MAX_VALUE;
        double resultMinimumDouble = Double.MAX_VALUE;
        MongoCursor<Document> cursor = it.iterator();
        while (cursor.hasNext()) {
            Document doc = cursor.next();
            Document eventProps = (Document) doc.get("eventProperties");
            if (longProperty) {
                long value = (Long) eventProps.get(this.propertyKey);
                if (value < resultMinimumLong)
                    resultMinimumLong = value;
            } else if (doubleProperty) {
                double value = (Double) eventProps.get(this.propertyKey);
                if (value < resultMinimumDouble)
                    resultMinimumDouble = value;
            }
        }

        if (longProperty) {
            long resultMinimum = resultMinimumLong;
            Document resultDoc = new Document("RESULT", resultMinimum);
            foundDocuments.add(resultDoc);
        } else if (doubleProperty) {
            double resultMinimum = resultMinimumDouble;
            Document resultDoc = new Document("RESULT", resultMinimum);
            foundDocuments.add(resultDoc);
        }
    }

    if (queryType.equals(EventQueryType.PREDICTED) && queryOperation.equals(EventQueryOperation.DEFAULT)) {
        FindIterable<Document> it = collection
                .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime)));

        MongoCursor<Document> cursor = it.iterator();
        while (cursor.hasNext()) {
            Document doc = cursor.next();
            foundDocuments.add(doc);
        }
    }

    if (queryType.equals(EventQueryType.PREDICTED) && queryOperation.equals(EventQueryOperation.AVERAGE)) {
        FindIterable<Document> it = collection
                .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime)));

        boolean longProperty = false;
        boolean doubleProperty = false;
        MongoCursor<Document> firstCursor = it.iterator();
        if (firstCursor.hasNext()) {
            Document doc = firstCursor.next();
            Document eventProps = (Document) doc.get("eventProperties");
            Object valueObj = eventProps.get(this.propertyKey);
            if (valueObj instanceof Long)
                longProperty = true;
            else if (valueObj instanceof Double)
                doubleProperty = true;
        }

        long resultAverageLong = 0;
        double resultAverageDouble = 0;
        long collectionSize = 0;
        MongoCursor<Document> cursor = it.iterator();
        while (cursor.hasNext()) {
            collectionSize++;
            Document doc = cursor.next();
            Document eventProps = (Document) doc.get("eventProperties");
            if (longProperty) {
                long value = (Long) eventProps.get(this.propertyKey);
                resultAverageLong = resultAverageLong + value;
            } else if (doubleProperty) {
                double value = (Double) eventProps.get(this.propertyKey);
                resultAverageDouble = resultAverageDouble + value;
            }
        }

        if (longProperty) {
            long resultAverage = resultAverageLong / collectionSize;
            Document resultDoc = new Document("RESULT", resultAverage);
            foundDocuments.add(resultDoc);
        } else if (doubleProperty) {
            double resultAverage = resultAverageDouble / collectionSize;
            Document resultDoc = new Document("RESULT", resultAverage);
            foundDocuments.add(resultDoc);
        }
    }

    if (queryType.equals(EventQueryType.PREDICTED) && queryOperation.equals(EventQueryOperation.MAXIMUM)) {
        FindIterable<Document> it = collection
                .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime)));

        boolean longProperty = false;
        boolean doubleProperty = false;
        MongoCursor<Document> firstCursor = it.iterator();
        if (firstCursor.hasNext()) {
            Document doc = firstCursor.next();
            Document eventProps = (Document) doc.get("eventProperties");
            Object valueObj = eventProps.get(this.propertyKey);
            if (valueObj instanceof Long)
                longProperty = true;
            else if (valueObj instanceof Double)
                doubleProperty = true;
        }

        long resultMaximumLong = Long.MIN_VALUE;
        double resultMaximumDouble = Double.MIN_VALUE;
        MongoCursor<Document> cursor = it.iterator();
        while (cursor.hasNext()) {
            Document doc = cursor.next();
            Document eventProps = (Document) doc.get("eventProperties");
            if (longProperty) {
                long value = (Long) eventProps.get(this.propertyKey);
                if (value > resultMaximumLong)
                    resultMaximumLong = value;
            } else if (doubleProperty) {
                double value = (Double) eventProps.get(this.propertyKey);
                if (value > resultMaximumDouble)
                    resultMaximumDouble = value;
            }
        }

        if (longProperty) {
            long resultMaximum = resultMaximumLong;
            Document resultDoc = new Document("RESULT", resultMaximum);
            foundDocuments.add(resultDoc);
        } else if (doubleProperty) {
            double resultMaximum = resultMaximumDouble;
            Document resultDoc = new Document("RESULT", resultMaximum);
            foundDocuments.add(resultDoc);
        }
    }

    if (queryType.equals(EventQueryType.PREDICTED) && queryOperation.equals(EventQueryOperation.MINUMUM)) {
        FindIterable<Document> it = collection
                .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime)));

        boolean longProperty = false;
        boolean doubleProperty = false;
        MongoCursor<Document> firstCursor = it.iterator();
        if (firstCursor.hasNext()) {
            Document doc = firstCursor.next();
            Document eventProps = (Document) doc.get("eventProperties");
            Object valueObj = eventProps.get(this.propertyKey);
            if (valueObj instanceof Long)
                longProperty = true;
            else if (valueObj instanceof Double)
                doubleProperty = true;
        }

        long resultMinimumLong = Long.MAX_VALUE;
        double resultMinimumDouble = Double.MAX_VALUE;
        MongoCursor<Document> cursor = it.iterator();
        while (cursor.hasNext()) {
            Document doc = cursor.next();
            Document eventProps = (Document) doc.get("eventProperties");
            if (longProperty) {
                long value = (Long) eventProps.get(this.propertyKey);
                if (value < resultMinimumLong)
                    resultMinimumLong = value;
            } else if (doubleProperty) {
                double value = (Long) eventProps.get(this.propertyKey);
                if (value < resultMinimumDouble)
                    resultMinimumDouble = value;
            }
        }

        if (longProperty) {
            long resultMinimum = resultMinimumLong;
            Document resultDoc = new Document("RESULT", resultMinimum);
            foundDocuments.add(resultDoc);
        } else if (doubleProperty) {
            double resultMinimum = resultMinimumDouble;
            Document resultDoc = new Document("RESULT", resultMinimum);
            foundDocuments.add(resultDoc);
        }
    }

    if (queryType.equals(EventQueryType.ANOMALY) && queryOperation.equals(EventQueryOperation.DEFAULT)) {
        FindIterable<Document> it = collection
                .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime)));

        MongoCursor<Document> cursor = it.iterator();
        while (cursor.hasNext()) {
            Document doc = cursor.next();
            foundDocuments.add(doc);
        }
    }

    if (queryType.equals(EventQueryType.RECOMMENDATION) && queryOperation.equals(EventQueryOperation.DEFAULT)) {
        FindIterable<Document> it = collection
                .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime)));

        MongoCursor<Document> cursor = it.iterator();
        while (cursor.hasNext()) {
            Document doc = cursor.next();
            foundDocuments.add(doc);
        }
    }

    if (queryType.equals(EventQueryType.RECOMMENDATION) && queryOperation.equals(EventQueryOperation.AVERAGE)) {
        FindIterable<Document> it = collection
                .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime)));

        boolean longProperty = false;
        boolean doubleProperty = false;
        MongoCursor<Document> firstCursor = it.iterator();
        if (firstCursor.hasNext()) {
            Document doc = firstCursor.next();
            Document eventProps = (Document) doc.get("eventProperties");
            Object valueObj = eventProps.get(this.propertyKey);
            if (valueObj instanceof Long)
                longProperty = true;
            else if (valueObj instanceof Double)
                doubleProperty = true;
        }

        long resultAverageLong = 0;
        double resultAverageDouble = 0;
        long collectionSize = 0;
        MongoCursor<Document> cursor = it.iterator();
        while (cursor.hasNext()) {
            collectionSize++;
            Document doc = cursor.next();
            Document eventProps = (Document) doc.get("eventProperties");
            if (longProperty) {
                long value = (Long) eventProps.get(this.propertyKey);
                resultAverageLong = resultAverageLong + value;
            } else if (doubleProperty) {
                double value = (Double) eventProps.get(this.propertyKey);
                resultAverageDouble = resultAverageDouble + value;
            }
        }

        if (longProperty) {
            long resultAverage = resultAverageLong / collectionSize;
            Document resultDoc = new Document("RESULT", resultAverage);
            foundDocuments.add(resultDoc);
        } else if (doubleProperty) {
            double resultAverage = resultAverageDouble / collectionSize;
            Document resultDoc = new Document("RESULT", resultAverage);
            foundDocuments.add(resultDoc);
        }
    }

    if (queryType.equals(EventQueryType.RECOMMENDATION) && queryOperation.equals(EventQueryOperation.MAXIMUM)) {
        FindIterable<Document> it = collection
                .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime)));

        boolean longProperty = false;
        boolean doubleProperty = false;
        MongoCursor<Document> firstCursor = it.iterator();
        if (firstCursor.hasNext()) {
            Document doc = firstCursor.next();
            Document eventProps = (Document) doc.get("eventProperties");
            Object valueObj = eventProps.get(this.propertyKey);
            if (valueObj instanceof Long)
                longProperty = true;
            else if (valueObj instanceof Double)
                doubleProperty = true;
        }

        long resultMaximumLong = Long.MIN_VALUE;
        double resultMaximumDouble = Double.MIN_VALUE;
        MongoCursor<Document> cursor = it.iterator();
        while (cursor.hasNext()) {
            Document doc = cursor.next();
            Document eventProps = (Document) doc.get("eventProperties");
            if (longProperty) {
                long value = (Long) eventProps.get(this.propertyKey);
                if (value > resultMaximumLong)
                    resultMaximumLong = value;
            } else if (doubleProperty) {
                double value = (Double) eventProps.get(this.propertyKey);
                if (value > resultMaximumDouble)
                    resultMaximumDouble = value;
            }
        }

        if (longProperty) {
            long resultMaximum = resultMaximumLong;
            Document resultDoc = new Document("RESULT", resultMaximum);
            foundDocuments.add(resultDoc);
        } else if (doubleProperty) {
            double resultMaximum = resultMaximumDouble;
            Document resultDoc = new Document("RESULT", resultMaximum);
            foundDocuments.add(resultDoc);
        }
    }

    if (queryType.equals(EventQueryType.RECOMMENDATION) && queryOperation.equals(EventQueryOperation.MINUMUM)) {
        FindIterable<Document> it = collection
                .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime)));

        boolean longProperty = false;
        boolean doubleProperty = false;
        MongoCursor<Document> firstCursor = it.iterator();
        if (firstCursor.hasNext()) {
            Document doc = firstCursor.next();
            Document eventProps = (Document) doc.get("eventProperties");
            Object valueObj = eventProps.get(this.propertyKey);
            if (valueObj instanceof Long)
                longProperty = true;
            else if (valueObj instanceof Double)
                doubleProperty = true;
        }

        long resultMinimumLong = Long.MAX_VALUE;
        double resultMinimumDouble = Double.MAX_VALUE;
        MongoCursor<Document> cursor = it.iterator();
        while (cursor.hasNext()) {
            Document doc = cursor.next();
            Document eventProps = (Document) doc.get("eventProperties");
            if (longProperty) {
                long value = (Long) eventProps.get(this.propertyKey);
                if (value < resultMinimumLong)
                    resultMinimumLong = value;
            } else if (doubleProperty) {
                double value = (Double) eventProps.get(this.propertyKey);
                if (value < resultMinimumDouble)
                    resultMinimumDouble = value;
            }
        }

        if (longProperty) {
            long resultMinimum = resultMinimumLong;
            Document resultDoc = new Document("RESULT", resultMinimum);
            foundDocuments.add(resultDoc);
        } else if (doubleProperty) {
            double resultMinimum = resultMinimumDouble;
            Document resultDoc = new Document("RESULT", resultMinimum);
            foundDocuments.add(resultDoc);
        }
    }

    if (queryType.equals(EventQueryType.FEEDBACK) && queryOperation.equals(EventQueryOperation.DEFAULT)) {
        FindIterable<Document> it = collection
                .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime)));

        MongoCursor<Document> cursor = it.iterator();
        while (cursor.hasNext()) {
            Document doc = cursor.next();
            foundDocuments.add(doc);
        }
    }

    mongoClient.close();

    return foundDocuments;
}

From source file:net.netzgut.integral.mongo.internal.services.MongoODMImplementation.java

License:Apache License

@Override
public <T extends Serializable> Stream<T> find(Bson filter, Class<T> entityClass) {
    MongoCollection<Document> collection = this.mongo.getCollection(entityClass);
    FindIterable<Document> find = collection.find(filter);
    return this.converter.entitiesStreamFrom(find, entityClass);
}

From source file:net.netzgut.integral.mongo.internal.services.MongoODMImplementation.java

License:Apache License

@Override
public <T extends Serializable> T findFirst(Bson filter, Class<T> entityClass) {
    MongoCollection<Document> collection = this.mongo.getCollection(entityClass);
    Document document = collection.find(filter).limit(1).first();
    if (document == null) {
        return null;
    }//from   w  ww  .ja v a 2 s .  c om
    return this.converter.entityFrom(document, entityClass);
}

From source file:nl.syntouch.oracle.adapter.cloud.mongodb.sample.MongoDBSample.java

License:Apache License

public static void main(String[] args) {
    // connect to MongoDB at localhost:27017
    MongoClient mongoClient = new MongoClient();

    // switch to test db
    MongoDatabase database = mongoClient.getDatabase("test");

    // drop test collection (note the collection will always be created by the getCollection command)
    MongoCollection<Document> collection = database.getCollection("test");
    collection.drop();/* ww  w .  ja va2  s. co  m*/

    // create a new collection
    collection = database.getCollection("test");

    // create BSON document and save it
    Document doc = new Document().append("field1", "value1");
    collection.insertOne(doc);
    System.out.println(doc.toString());

    Document queryDoc1 = new Document().append("_id", doc.get("_id"));
    System.out.println(collection.find(queryDoc1).first().toString());

    Document queryDoc2 = new Document().append("field1", doc.get("field1"));
    System.out.println(collection.find(queryDoc2).first().toString());
}

From source file:org.apache.drill.exec.store.mongo.MongoGroupScan.java

License:Apache License

@SuppressWarnings({ "rawtypes" })
private void init() throws IOException {

    List<String> h = storagePluginConfig.getHosts();
    List<ServerAddress> addresses = Lists.newArrayList();
    for (String host : h) {
        addresses.add(new ServerAddress(host));
    }/*w ww  . ja v a 2s . c o m*/
    MongoClient client = storagePlugin.getClient();
    chunksMapping = Maps.newHashMap();
    chunksInverseMapping = Maps.newLinkedHashMap();
    if (isShardedCluster(client)) {
        MongoDatabase db = client.getDatabase(CONFIG);
        MongoCollection<Document> chunksCollection = db.getCollection(CHUNKS);
        Document filter = new Document();
        filter.put(NS, this.scanSpec.getDbName() + "." + this.scanSpec.getCollectionName());

        Document projection = new Document();
        projection.put(SHARD, select);
        projection.put(MIN, select);
        projection.put(MAX, select);

        FindIterable<Document> chunkCursor = chunksCollection.find(filter).projection(projection);
        MongoCursor<Document> iterator = chunkCursor.iterator();

        MongoCollection<Document> shardsCollection = db.getCollection(SHARDS);

        projection = new Document();
        projection.put(HOST, select);

        boolean hasChunks = false;
        while (iterator.hasNext()) {
            Document chunkObj = iterator.next();
            String shardName = (String) chunkObj.get(SHARD);
            String chunkId = (String) chunkObj.get(ID);
            filter = new Document(ID, shardName);
            FindIterable<Document> hostCursor = shardsCollection.find(filter).projection(projection);
            MongoCursor<Document> hostIterator = hostCursor.iterator();
            while (hostIterator.hasNext()) {
                Document hostObj = hostIterator.next();
                String hostEntry = (String) hostObj.get(HOST);
                String[] tagAndHost = StringUtils.split(hostEntry, '/');
                String[] hosts = tagAndHost.length > 1 ? StringUtils.split(tagAndHost[1], ',')
                        : StringUtils.split(tagAndHost[0], ',');
                List<String> chunkHosts = Arrays.asList(hosts);
                Set<ServerAddress> addressList = getPreferredHosts(storagePlugin.getClient(addresses),
                        chunkHosts);
                if (addressList == null) {
                    addressList = Sets.newHashSet();
                    for (String host : chunkHosts) {
                        addressList.add(new ServerAddress(host));
                    }
                }
                chunksMapping.put(chunkId, addressList);
                ServerAddress address = addressList.iterator().next();
                List<ChunkInfo> chunkList = chunksInverseMapping.get(address.getHost());
                if (chunkList == null) {
                    chunkList = Lists.newArrayList();
                    chunksInverseMapping.put(address.getHost(), chunkList);
                }
                List<String> chunkHostsList = new ArrayList<String>();
                for (ServerAddress serverAddr : addressList) {
                    chunkHostsList.add(serverAddr.toString());
                }
                ChunkInfo chunkInfo = new ChunkInfo(chunkHostsList, chunkId);
                Document minMap = (Document) chunkObj.get(MIN);

                Map<String, Object> minFilters = Maps.newHashMap();
                Set keySet = minMap.keySet();
                for (Object keyObj : keySet) {
                    Object object = minMap.get(keyObj);
                    if (!(object instanceof MinKey)) {
                        minFilters.put(keyObj.toString(), object);
                    }
                }
                chunkInfo.setMinFilters(minFilters);

                Map<String, Object> maxFilters = Maps.newHashMap();
                Map maxMap = (Document) chunkObj.get(MAX);
                keySet = maxMap.keySet();
                for (Object keyObj : keySet) {
                    Object object = maxMap.get(keyObj);
                    if (!(object instanceof MaxKey)) {
                        maxFilters.put(keyObj.toString(), object);
                    }
                }

                chunkInfo.setMaxFilters(maxFilters);
                chunkList.add(chunkInfo);
            }
            hasChunks = true;
        }
        // In a sharded environment, if a collection doesn't have any chunks, it is considered as an
        // unsharded collection and it will be stored in the primary shard of that database.
        if (!hasChunks) {
            handleUnshardedCollection(getPrimaryShardInfo(client));
        }
    } else {
        handleUnshardedCollection(storagePluginConfig.getHosts());
    }

}

From source file:org.apache.drill.exec.store.mongo.MongoGroupScan.java

License:Apache License

private List<String> getPrimaryShardInfo(MongoClient client) {
    MongoDatabase database = storagePlugin.getClient().getDatabase(CONFIG);
    //Identify the primary shard of the queried database.
    MongoCollection<Document> collection = database.getCollection(DATABASES);
    Bson filter = new Document(ID, this.scanSpec.getDbName());
    Bson projection = new Document(PRIMARY, select);
    Document document = collection.find(filter).projection(projection).first();
    Preconditions.checkNotNull(document);
    String shardName = document.getString(PRIMARY);
    Preconditions.checkNotNull(shardName);

    //Identify the host(s) on which this shard resides.
    MongoCollection<Document> shardsCol = database.getCollection(SHARDS);
    filter = new Document(ID, shardName);
    projection = new Document(HOST, select);
    Document hostInfo = shardsCol.find(filter).projection(projection).first();
    Preconditions.checkNotNull(hostInfo);
    String hostEntry = hostInfo.getString(HOST);
    Preconditions.checkNotNull(hostEntry);

    String[] tagAndHost = StringUtils.split(hostEntry, '/');
    String[] hosts = tagAndHost.length > 1 ? StringUtils.split(tagAndHost[1], ',')
            : StringUtils.split(tagAndHost[0], ',');
    return Lists.newArrayList(hosts);
}