Example usage for com.mongodb.client MongoDatabase getCollection

List of usage examples for com.mongodb.client MongoDatabase getCollection

Introduction

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

Prototype

MongoCollection<Document> getCollection(String collectionName);

Source Link

Document

Gets a collection.

Usage

From source file:com.px100systems.data.plugin.storage.mongo.MongoDatabaseStorage.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public <T> List<T> search(String unitName, Class<T> cls, Criteria criteria, List<String> orderBy,
        Integer limit) {//  ww w .  ja  v  a  2 s  . com
    SerializationDefinition def = SerializationDefinition.get(cls);
    if (def == null)
        throw new RuntimeException("Cannot find SerializationDefinition for " + cls.getSimpleName());

    MongoDatabase db = mongoClient.getDatabase(databaseName);

    FindIterable<Document> query = criteria == null ? db.getCollection(unitName).find()
            : db.getCollection(unitName).find(criteria.convert(new FilterQueryBuilder()));

    if (orderBy != null && !orderBy.isEmpty())
        if (orderBy.size() == 1)
            query = query.sort(orderBy(orderBy.get(0)));
        else {
            List<Bson> ob = new ArrayList<>();
            for (String s : orderBy)
                ob.add(orderBy(s));
            query = query.sort(Sorts.orderBy(ob));
        }

    List<T> result = new ArrayList<>();
    MongoCursor<Document> cursor = query.limit(limit).iterator();
    try {
        while (cursor.hasNext()) {
            T item = (T) def.newInstance();
            def.read(cursor.next(), item);
            result.add(item);
        }
    } finally {
        cursor.close();
    }

    return result;
}

From source file:com.px100systems.data.plugin.storage.mongo.MongoDatabaseStorage.java

License:Open Source License

@Override
public <T> EntityCursor<T> search(String unitName, Class<T> cls, Criteria criteria, List<String> orderBy) {
    SerializationDefinition def = SerializationDefinition.get(cls);
    if (def == null)
        throw new RuntimeException("Cannot find SerializationDefinition for " + cls.getSimpleName());

    MongoDatabase db = mongoClient.getDatabase(databaseName);

    FindIterable<Document> query = criteria == null ? db.getCollection(unitName).find()
            : db.getCollection(unitName).find(criteria.convert(new FilterQueryBuilder()));

    if (orderBy != null && !orderBy.isEmpty())
        if (orderBy.size() == 1)
            query = query.sort(orderBy(orderBy.get(0)));
        else {// ww w  .j a  va 2 s. c  o m
            List<Bson> ob = new ArrayList<>();
            for (String s : orderBy)
                ob.add(orderBy(s));
            query = query.sort(Sorts.orderBy(ob));
        }

    return new ResultIterator<T>(query.iterator(), def);
}

From source file:com.px100systems.data.plugin.storage.mongo.MongoDatabaseStorage.java

License:Open Source License

public long count(String unitName, Class<?> cls, Criteria criteria) {
    MongoDatabase db = mongoClient.getDatabase(databaseName);
    return criteria == null ? db.getCollection(unitName).count()
            : db.getCollection(unitName).count(criteria.convert(new FilterQueryBuilder()));
}

From source file:com.px100systems.data.plugin.storage.mongo.MongoDatabaseStorage.java

License:Open Source License

private void batchSave(MongoDatabase db, List<StoredBean> inserts, List<StoredBean> updates,
        List<Delete> deletes) {
    Map<String, List<WriteModel<Document>>> batches = new HashMap<>();

    for (StoredBean bean : inserts) {
        String unitName = bean.unitName();
        List<WriteModel<Document>> batch = batches.get(unitName);
        if (batch == null) {
            batch = new ArrayList<>();
            batches.put(unitName, batch);
        }/*from w  w  w  . j  a va  2s . com*/

        batch.add(new InsertOneModel<Document>(serialize(bean)));
    }

    for (StoredBean bean : updates) {
        String unitName = bean.unitName();
        List<WriteModel<Document>> batch = batches.get(unitName);
        if (batch == null) {
            batch = new ArrayList<>();
            batches.put(unitName, batch);
        }

        batch.add(new ReplaceOneModel<Document>(Filters.eq("id", bean.getId()), serialize(bean)));
    }

    for (Delete delete : deletes) {
        String unitName = delete.getUnitName();
        List<WriteModel<Document>> batch = batches.get(unitName);
        if (batch == null) {
            batch = new ArrayList<>();
            batches.put(unitName, batch);
        }

        batch.add(delete.getId() == null
                ? new DeleteManyModel<Document>(delete.getCriteria().convert(new FilterQueryBuilder()))
                : new DeleteOneModel<Document>(Filters.eq("id", delete.getId())));
    }

    for (Map.Entry<String, List<WriteModel<Document>>> e : batches.entrySet())
        db.getCollection(e.getKey()).bulkWrite(e.getValue());
}

From source file:com.shiyq.mongodb.BulkInsertThread.java

@Override
public void run() {
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    MongoDatabase mongoDatabase = mongoClient.getDatabase("study");

    MongoCollection<Document> collection = mongoDatabase.getCollection("s_user");
    List<Document> list = new ArrayList<>();
    Document document;/*from   www.ja  va2s . co  m*/

    int i = 0;
    while (true) {
        if (i++ < 1000) {
            document = new Document();
            document.append("id", UUID.randomUUID());
            document.append("code", code);
            document.append("name", name);
            document.append("password", password);
            document.append("create_date", new Date());
            list.add(document);
        } else {
            //System.out.println(list.size());
            collection.insertMany(list);
            list.clear();
            i = 0;
        }
    }
}

From source file:com.shiyq.mongodb.InsertThread.java

@Override
public void run() {
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    MongoDatabase mongoDatabase = mongoClient.getDatabase("study");

    MongoCollection<Document> collection = mongoDatabase.getCollection("s_user");
    Document document;//w  w  w .  j  a  v  a2 s . c om
    while (true) {
        document = new Document();
        document.append("code", code);
        document.append("name", name);
        document.append("password", password);
        document.append("create_date", new Date());

        collection.insertOne(document);
    }
}

From source file:com.sparkjava.MongoDBSparkFreemarkerStyle.java

License:Apache License

public static void main(String[] args) {
    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(MongoDBSparkFreemarkerStyle.class, "/freemarker");

    MongoClient client = new MongoClient();

    MongoDatabase database = client.getDatabase("m101");
    final MongoCollection<Document> collection = database.getCollection("funnynumbers");

    //        Spark.get("/", new Route() {
    //            
    //            public Object handle(final Request request,
    //                                 final Response response) {
    //                StringWriter writer = new StringWriter();
    //                try {
    //                    Template template = configuration.getTemplate("answer.ftl");
    ///*from w  w  w .j av a 2s  .  c o m*/
    //                    // Not necessary yet to understand this.  It's just to prove that you
    //                    // are able to run a command on a mongod server
    //                    List<Document> results =
    //                    collection.aggregate(asList(new Document("$group", new Document("_id", "$value")
    //                                                                       .append("count", new Document("$sum", 1))),
    //                                                new Document("$match", new Document("count", new Document("$lte", 2))),
    //                                                new Document("$sort", new Document("_id", 1))))
    //                              .into(new ArrayList<Document>());
    //
    //                    int answer = 0;
    //                    for (Document cur : results) {
    //                        answer += (Double) cur.get("_id");
    //                    }
    //
    //                    Map<String, String> answerMap = new HashMap<String, String>();
    //                    answerMap.put("answer", Integer.toString(answer));
    //
    //                    template.process(answerMap, writer);
    //                } catch (Exception e) {
    //                    e.printStackTrace();
    ////                    halt(500);
    //                }
    //                return writer;
    //            }
    //        });
}

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 -> {/*from w w  w .ja va2 s  .  c  o  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.streamsets.pipeline.stage.destination.mongodb.MongoDBTarget.java

License:Apache License

@Override
protected List<ConfigIssue> init() {
    List<ConfigIssue> issues = super.init();

    errorRecordHandler = new DefaultErrorRecordHandler(getContext());
    MongoClientURI connectionString = new MongoClientURI(mongoTargetConfigBean.mongoClientURI);
    mongoClient = new MongoClient(connectionString);
    MongoDatabase db = mongoClient.getDatabase(mongoTargetConfigBean.database);
    coll = db.getCollection(mongoTargetConfigBean.collection)
            .withWriteConcern(mongoTargetConfigBean.writeConcern.getWriteConcern());

    DataGeneratorFactoryBuilder builder = new DataGeneratorFactoryBuilder(getContext(),
            DataFormat.JSON.getGeneratorFormat());
    builder.setCharset(StandardCharsets.UTF_8);

    builder.setMode(JsonMode.MULTIPLE_OBJECTS);
    generatorFactory = builder.build();/*from w  w w . jav  a  2s .  co m*/

    return issues;
}

From source file:com.techngage.smartbin.LocationDAO.java

License:Apache License

public LocationDAO(final MongoDatabase smartbinDatabase) {
    locationCollection = smartbinDatabase.getCollection("location");
}