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.shampan.model.PageModel.java

public List<String> getPageIdList(String userId) {
    MongoCollection<PageMemberDAO> mongoCollection = DBConnection.getInstance().getConnection()
            .getCollection(Collections.PAGEMEMBERS.toString(), PageMemberDAO.class);
    MongoCursor<PageMemberDAO> pageList = mongoCollection.find().iterator();
    List<String> pageIdList = new ArrayList<>();
    while (pageList.hasNext()) {
        PageMemberDAO pageInfo = pageList.next();
        if (pageInfo.getMemberList().size() > 0) {
            for (int i = 0; i < pageInfo.getMemberList().size(); i++) {

                if (pageInfo.getMemberList().get(i).getUserId().equals(userId)) {
                    pageIdList.add(pageInfo.getPageId());
                }/*from   w  w w  .j  av a  2s  .  c  o  m*/
            }
        }
    }
    return pageIdList;
}

From source file:com.shampan.model.UserModel.java

public List<JSONObject> getRecentUser() {
    int offset = 0;
    int limit = 10;
    MongoCollection<UserDAO> mongoCollection = DBConnection.getInstance().getConnection()
            .getCollection(Collections.USERS.toString(), UserDAO.class);
    Document projectionDocument = new Document();
    projectionDocument.put("firstName", "$all");
    projectionDocument.put("lastName", "$all");
    projectionDocument.put("userId", "$all");
    projectionDocument.put("gender", "$all");
    projectionDocument.put("country", "$all");
    List<JSONObject> requestList = new ArrayList<JSONObject>();
    List<UserDAO> userInfoList = new ArrayList<>();
    MongoCursor<UserDAO> userList = mongoCollection.find().sort(new Document("modifiedOn", -1)).skip(offset)
            .limit(limit).projection(projectionDocument).iterator();
    List<String> userIds = new ArrayList<>();
    while (userList.hasNext()) {
        UserDAO user = userList.next();/*from   w  w  w  . ja v a2 s. com*/
        userIds.add(user.getUserId());
        userInfoList.add(user);

    }

    List<BasicProfileDAO> userBasicInfoList = basicProfileModel.getRecentUserInfo(userIds.toString());
    if (userBasicInfoList != null) {
        int userSize = userBasicInfoList.size();
        int userListSize = userInfoList.size();
        for (int j = 0; j < userSize; j++) {
            for (int i = 0; i < userListSize; i++) {
                if (userInfoList.get(i).getUserId().equals(userBasicInfoList.get(j).getUserId())) {
                    //                        BirthDate birthDay = userBasicInfoList.get(j).getBasicInfo().getBirthDate();

                    JSONObject userJson = new JSONObject();
                    //                        int age = getAge(birthDay);
                    //                        userJson.put("age", age);
                    userJson.put("userId", userInfoList.get(i).getUserId());
                    userJson.put("firstName", userInfoList.get(i).getFirstName());
                    userJson.put("lastName", userInfoList.get(i).getLastName());
                    userJson.put("gender", userInfoList.get(i).getGender());
                    userJson.put("country", userInfoList.get(i).getCountry());
                    if (userBasicInfoList.get(j).getBasicInfo().getCity() != null) {
                        userJson.put("city", userBasicInfoList.get(j).getBasicInfo().getCity().getCityName());
                    }
                    if (userBasicInfoList.get(j).getpSkills() != null) {
                        int pSkillSize = userBasicInfoList.get(j).getpSkills().size();
                        userJson.put("pSkill",
                                userBasicInfoList.get(j).getpSkills().get(pSkillSize - 1).getpSkill());
                    }
                    requestList.add(userJson);
                }
            }
        }
    }

    return requestList;
}

From source file:com.shampan.model.VideoModel.java

/**
 * This method will return video categories
 *
 * @author created by Rashida on 21 October
 *//*from   w  w  w  .  j a v a2  s.c o  m*/
public List<VideoCategoryDAO> getVideoCategories() {
    MongoCollection<VideoCategoryDAO> mongoCollection = DBConnection.getInstance().getConnection()
            .getCollection(Collections.VIDEOCATEGORIES.toString(), VideoCategoryDAO.class);
    MongoCursor<VideoCategoryDAO> cursorCategoryList = mongoCollection.find().iterator();
    List<VideoCategoryDAO> categoryList = IteratorUtils.toList(cursorCategoryList);
    return categoryList;

}

From source file:com.sitewhere.user.persistence.mongodb.MongoUserManagement.java

License:Open Source License

@Override
public List<IGrantedAuthority> listGrantedAuthorities(IGrantedAuthoritySearchCriteria criteria)
        throws SiteWhereException {
    try {//  www . j av a 2 s  .co  m
        MongoCollection<Document> auths = getMongoClient().getAuthoritiesCollection();
        FindIterable<Document> found = auths.find()
                .sort(new BasicDBObject(MongoGrantedAuthority.PROP_AUTHORITY, 1));
        MongoCursor<Document> cursor = found.iterator();

        List<IGrantedAuthority> matches = new ArrayList<IGrantedAuthority>();
        try {
            while (cursor.hasNext()) {
                Document match = cursor.next();
                matches.add(MongoGrantedAuthority.fromDBObject(match));
            }
        } finally {
            cursor.close();
        }
        return matches;
    } catch (MongoTimeoutException e) {
        throw new SiteWhereException("Connection to MongoDB lost.", e);
    }
}

From source file:com.speedment.connector.mongodb.MongoDbmsHandler.java

License:Open Source License

private Stream<Schema> populatedSchemas(MongoDatabase mongo) {
    final Map<String, Schema> schemas = schemasUnpopulated().collect(toMap(Schema::getName, identity()));

    return collectionNames(mongo)

            .map(fullName -> {/* w  w  w  .j a va 2 s  .  co  m*/
                final String schemaName = collectionNameToSchemaName(fullName);
                final Schema schema = schemas.get(schemaName);

                final Optional<String> tableName = collectionNameToTableName(fullName);

                if (tableName.isPresent()) {

                    final Table table = schema.addNewTable();
                    table.setName(tableName.get());
                    table.setTableName(tableName.get());

                    final MongoCollection<Document> col = mongo.getCollection(fullName);
                    final Document doc = col.find().first();

                    doc.entrySet().forEach(entry -> {
                        final Column column = table.addNewColumn();

                        column.setName(entry.getKey());
                        column.setNullable(true);
                        column.setMapping(determineMapping(doc, entry.getKey()));

                        if (PK.equals(entry.getKey())) {
                            final PrimaryKeyColumn pk = table.addNewPrimaryKeyColumn();
                            pk.setName(PK);
                        }
                    });
                }

                return schema;
            })

            .distinct();
}

From source file:com.threecrickets.prudence.cache.HazelcastMongoDbMapStore.java

License:LGPL

public Set<K> loadAllKeys() {
    MongoCollection<Document> collection = getCollection();
    Document projection = new Document();

    projection.put("_id", 1);

    Set<K> keys = new HashSet<K>();
    for (Document value : collection.find().projection(projection)) {
        @SuppressWarnings("unchecked")
        K id = (K) value.get("_id");
        keys.add(id);/*from  ww  w . j av  a2  s .c o  m*/
    }

    return keys;
}

From source file:controller.ProductController.java

public int getIndex() {
    Document doc = new Document();
    MongoCollection<Document> col = db.getCollection("product");
    if (col.count() <= 0)
        return 0;
    for (Document d : col.find())
        doc = d;//  w w  w  . j a  v  a 2s.  c o  m
    int j = (int) doc.get("itemId");
    return j + 1;
}

From source file:course.homework.Homework3.java

License:Apache License

public static void main(String[] args) {

    MongoClient client = new MongoClient();
    MongoDatabase database = client.getDatabase("school");
    MongoCollection<Document> collection = database.getCollection("students");

    MongoCursor<Document> iterator = collection.find().iterator();
    while (iterator.hasNext()) {
        Document doc = iterator.next();
        List<Document> scores = (List<Document>) doc.get("scores");

        Optional<Document> bestHomeWork = scores.stream()
                .max((a, b) -> a.getString("type").equals("homework") && b.getString("type").equals("homework")
                        ? Double.compare(a.getDouble("score"), b.getDouble("score"))
                        : -1);/*from  w  ww. jav  a2  s. c  o  m*/
        Double bestScore = bestHomeWork.get().getDouble("score");

        List<Document> result = scores.stream()
                .filter(x -> !x.getString("type").equals("homework") || x.getDouble("score").equals(bestScore))
                .collect(Collectors.toList());

        collection.updateOne(eq("_id", doc.get("_id")), new Document("$set", new Document("scores", result)));

    }
    iterator.close();
    client.close();

}

From source file:Dao.AccessDataNOSQL.java

License:Open Source License

/**
 * Mtodo para cargar en memoria las calificaciones
 *//*from   w w  w  .ja  va2 s.c o  m*/
@Override
public void cargarEventosDAO() {
    MongoCollection<Document> collec = consultaBD("nosql", "ratings");
    MongoCursor<Document> cursor = collec.find().iterator();

    while (cursor.hasNext()) {
        try {
            String stringjson = cursor.next().toJson();
            JSONObject obj1 = new JSONObject(stringjson);

            String userId = obj1.getString("userId");
            String movieID = obj1.getString("movieId");
            String rating = obj1.getString("rating");
            String timestamp = obj1.getString("timestamp");

            User u = new User(Integer.parseInt(userId));
            Item i = new Movie(Integer.parseInt(movieID));

            double rat = Double.parseDouble(rating);
            int tim = Integer.parseInt(timestamp);

            Events evento = new Events(u, (Movie) i, rat, tim);
            getEventsDAO().add(evento);

        } catch (JSONException ex) {
            Logger.getLogger(AccessDataNOSQL.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    cursor.close();
}

From source file:Dao.AccessDataNOSQL.java

License:Open Source License

/**
 * Metodo para cargar en memoria los elementos
 *
 *//*  w w w.ja v a2 s .com*/
@Override
public void cargarItemsDAO() {
    MongoCollection<Document> collec = consultaBD("nosql", "movies");

    MongoCursor<Document> cursor = collec.find().iterator();
    while (cursor.hasNext()) {
        try {
            String stringjson = cursor.next().toJson();
            //JsonReader jr=new JsonReader(stringjson);
            JSONObject obj1 = new JSONObject(stringjson);
            String movieId = obj1.getString("movieId");
            String title = obj1.getString("title");
            String genres = obj1.getString("genres");

            Movie peli = new Movie();
            peli.setId(Integer.parseInt(movieId));
            peli.setTitle(title);
            peli.setGenre(genres);

            getItemsDAO().add(peli);
        } catch (JSONException ex) {
            Logger.getLogger(AccessDataNOSQL.class.getName()).log(Level.SEVERE, null, ex);
            System.err.print("error en cargarItemsDAO en AccesoNoSQL");
        }
    }
    cursor.close();
}