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.jaeksoft.searchlib.crawler.database.DatabaseCrawlMongoDb.java

License:Open Source License

MongoCollection<Document> getCollection(MongoClient mongoClient) throws IOException {
    if (StringUtils.isEmpty(databaseName))
        throw new IOException("No database name.");
    MongoDatabase db = mongoClient.getDatabase(databaseName);
    if (StringUtils.isEmpty(collectionName))
        throw new IOException("No collection name.");
    return db.getCollection(collectionName);
}

From source file:com.jaeksoft.searchlib.crawler.database.DatabaseCrawlMongoDb.java

License:Open Source License

@Override
public String test() throws Exception {
    URI uri = new URI(getUrl());
    StringBuilder sb = new StringBuilder();
    if (!"mongodb".equals(uri.getScheme()))
        throw new SearchLibException(
                "Wrong scheme: " + uri.getScheme() + ". The URL should start with: mongodb://");
    MongoClient mongoClient = null;/*from w  ww . j  a v  a 2s.  c  o  m*/
    try {
        mongoClient = getMongoClient();
        sb.append("Connection established.");
        sb.append(StringUtils.LF);
        if (!StringUtils.isEmpty(databaseName)) {
            MongoDatabase db = mongoClient.getDatabase(databaseName);
            if (db == null)
                throw new SearchLibException("Database not found: " + databaseName);
            MongoIterable<String> collections = db.listCollectionNames();
            if (collections == null)
                throw new SearchLibException("No collection found.");
            sb.append("Collections found:");
            sb.append(StringUtils.LF);
            for (String collection : collections) {
                sb.append(collection);
                sb.append(StringUtils.LF);
            }
            if (!StringUtils.isEmpty(collectionName)) {
                MongoCollection<?> dbCollection = db.getCollection(collectionName);
                if (dbCollection == null)
                    throw new SearchLibException("Collection " + collectionName + " not found.");
                sb.append(
                        "Collection " + collectionName + " contains " + dbCollection.count() + " document(s).");
                sb.append(StringUtils.LF);
                if (!StringUtils.isEmpty(criteria)) {
                    long count = dbCollection.count(getCriteriaObject());
                    sb.append("Query returns " + count + " document(s).");
                    sb.append(StringUtils.LF);
                }
            }
        }
    } finally {
        if (mongoClient != null)
            mongoClient.close();
    }
    return sb.toString();
}

From source file:com.mlveda.dori.AddPageWebhook.java

private PageArray getPagesData(PageArray pages, String shopName) {

    MongoDatabase db = MongoProvider.getInstance();

    FindIterable<Document> collection = db.getCollection("facebook_pages").find(eq("shop_name", shopName));
    final ArrayList<PagesInsertData> pageList = new ArrayList<>();

    System.out.println();//www.j ava2  s  . c om
    System.out.println();

    //        System.out.println("document: " + document);
    collection.forEach(new Block<Document>() {
        @Override
        public void apply(Document document) {

            pageList.add(gson.fromJson(gson.toJson(document), PagesInsertData.class));

        }
    });
    //        BasicDBObject document = new BasicDBObject();
    //        QueryBuilder qb = new QueryBuilder().put("shop_name").is(shopName);
    ////        qb.or(new QueryBuilder().put("shop_name").is(shopName).get(), new QueryBuilder().put("published_at").notEquals(null).get());
    //        document.putAll(qb.get());

    // convert JSON to DBObject directly
    //            Document document = new Document("array", JSON.parse(gson.toJson(pages.getData())), new JSONCallback());
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);

    ArrayList<PagesInsertData> responseObject = new ArrayList<>();

    if (pages.getData().isEmpty()) {
        return new PageArray(responseObject, false);
    }

    for (PagesInsertData page : pages.getData()) {
        boolean found = false;

        page.setCreatedAt(format.format(Calendar.getInstance().getTime()));
        page.setUpdatedAt(format.format(Calendar.getInstance().getTime()));
        page.setShopName(shopName);

        Document document = Document.parse(gson.toJson(page));

        for (PagesInsertData facebookPage : pageList) {

            System.out.println("facebook id: " + facebookPage.getId() + " page id: " + page.getId());
            if (facebookPage.getId().equalsIgnoreCase(page.getId())) {
                System.out.println("facebook id: " + facebookPage.getId() + " page id: " + page.getId());
                page.setInstalled(facebookPage.isInstalled());
                page.setCreatedAt(facebookPage.getCreatedAt());

                document = Document.parse(gson.toJson(page));
                found = true;
                //                    break;
            }

        }

        if (found) {
            found = false;
            db.getCollection("facebook_pages").updateOne(new Document("id", page.getId()),
                    new Document("$set", document));
        } else {
            db.getCollection("facebook_pages").insertOne(document);
        }

        responseObject.add(page);

        //            collection.insertOne(document);
    }

    return new PageArray(responseObject, true);

}

From source file:com.mlveda.dori.SubscribePage.java

private boolean addPagesToDB(PagesInsertData pages, String shopName) {
    MongoDatabase db = MongoProvider.getInstance();

    FindIterable<Document> collection = db.getCollection("facebook_pages")
            .find(and(eq("shop_name", shopName), eq("id", pages.getId())));
    //        final ArrayList<PagesInsertData> pageList = new ArrayList<>();

    System.out.println();//from   w  w w.  j  a v a  2s.co m
    System.out.println();

    PagesInsertData facebookPage = gson.fromJson(gson.toJson(collection.first()), PagesInsertData.class);

    boolean found = false;
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);

    ArrayList<PagesInsertData> responseObject = new ArrayList<>();

    pages.setCreatedAt(format.format(Calendar.getInstance().getTime()));
    pages.setUpdatedAt(format.format(Calendar.getInstance().getTime()));
    pages.setShopName(shopName);

    Document document = Document.parse(gson.toJson(pages));

    if (facebookPage.getId().equalsIgnoreCase(pages.getId())) {
        pages.setInstalled(facebookPage.isInstalled());
        pages.setCreatedAt(facebookPage.getCreatedAt());

        document = Document.parse(gson.toJson(pages));
        found = true;
    }

    if (found) {
        found = false;
        db.getCollection("facebook_pages").updateOne(new Document("id", pages.getId()),
                new Document("$set", document));
    } else {
        db.getCollection("facebook_pages").insertOne(document);
    }

    System.out.println("Done");

    return true;

}

From source file:com.mlveda.dori.Webhook.java

public ArrayList<Collection> getCollectionList() {

    MongoDatabase db = MongoProvider.getInstance();

    //        MongoCollection<Product> products = db.getCollection("disneytoys.myshopify.com_products", Product.class);
    BasicDBObject document = new BasicDBObject();
    QueryBuilder qb = new QueryBuilder();
    qb.or(new QueryBuilder().put("handle").notEquals("frontpage").get(),
            new QueryBuilder().put("published_at").notEquals(null).get());
    document.putAll(qb.get());/*from  www  .j ava 2s . com*/

    FindIterable<Document> coll = db.getCollection("dakshal.myshopify.com_collections")
            .find(and(ne("title", "Frontpage"), ne("published_at", null)));
    //        FindIterable<Document> coll = db.getCollection("disneytoys.myshopify.com_collection").find(document);

    //        FindIterable<Document> foundDocument = coll.find(and(ne("title", "Frontpage"), ne("published_at", null)));
    final Type collectionType = new TypeToken<ArrayList<Collection>>() {
    }.getType();

    final ArrayList<Collection> collection = new ArrayList<>();

    System.out.println();
    System.out.println();

    System.out.println("document: " + document);
    coll.forEach(new Block<Document>() {
        @Override
        public void apply(Document document) {

            collection.add(gson.fromJson(gson.toJson(document), Collection.class));

            //                System.out.println("document: " + document);
            //                ArrayList<Collection> c = gson.fromJson(gson.toJson(document.get("collections")), collectionType);
            //                System.out.println("collection: " + c);
            //                if (!c.isEmpty()) {
            //                    collection.addAll(c);
            //                }
            //                collection.add(t);
        }
    });
    System.out.println("Collection: " + gson.toJson(collection));
    System.out.println();
    System.out.println();

    return collection;
}

From source file:com.mlveda.dori.Webhook.java

private void sendVarientList(String recepientID, Product product, int position, ResponseModel otherParams,
        PagesInsertData page) {//from w ww  .j ava  2  s . c om

    SendAttachments attachment = new SendAttachments();

    attachment.setType("template");

    SendPayload payload = new SendPayload();

    ArrayList<Element> elements = new ArrayList<Element>();

    payload.setTemplateType("generic");

    //        System.out.println("products: " + products.size());
    System.out.println("product is published");

    System.out.println("option size: " + product.getOptions().size() + "position: ----------->" + position);

    if (product.getOptions().size() + 2 <= position) {

        //            sendTextMessage(recepientID, "No more varients to show", page);
        MongoDatabase db = MongoProvider.getInstance();

        //            String ids[] = otherParams.split("@");
        int id = 0;
        System.out.println("collectionID: " + otherParams.getCollectionID() + "other params:----> "
                + gson.toJson(otherParams));

        FindIterable<Document> coll = db.getCollection("dakshal.myshopify.com_collections")
                .find(eq("id", otherParams.getCollectionID()));

        System.out.println();
        System.out.println();
        System.out.println("collection size:-> " + gson.toJson(coll.first()));
        System.out.println();
        System.out.println();

        Collection collection = gson.fromJson(gson.toJson(coll.first()), Collection.class);

        OUTER: for (id = 0; id < product.getVariants().size(); id++) {
            switch (position) {
            case 3:
                if (product.getVariants().get(id).getOption1().equalsIgnoreCase(otherParams.getOption1())) {
                    System.out.println("id:----->>> " + id);
                    break OUTER;
                }
                break;
            case 4:
                if (product.getVariants().get(id).getOption1().equalsIgnoreCase(otherParams.getOption1())
                        && product.getVariants().get(id).getOption2()
                                .equalsIgnoreCase(otherParams.getOption2())) {
                    System.out.println("id:----->>> " + id);
                    break OUTER;
                }
                break;
            case 5:
                if (product.getVariants().get(id).getOption1().equalsIgnoreCase(otherParams.getOption1())
                        && product.getVariants().get(id).getOption2().equalsIgnoreCase(otherParams.getOption2())
                        && product.getVariants().get(id).getOption3()
                                .equalsIgnoreCase(otherParams.getOption3())) {
                    System.out.println("id:----->>> " + id);
                    break OUTER;
                }
                break;
            }
        }

        if (id < product.getVariants().size()) {
            System.out.println("collection:----->>> " + gson.toJson(collection));
            System.out.println("page:----->>> " + gson.toJson(page));
            otherParams.setLength(otherParams.getLength() - 1);

            //            switch (otherParams.getLength()) {
            //                case 1:
            //                    otherParams.setOption1(null);
            //                    break;
            //                case 2:
            //                    otherParams.setOption2(null);
            //                    otherParams.setLength(otherParams.getLength() - 1);
            //                    break;
            //                case 3:
            //                    otherParams.setOption3(null);
            //                    otherParams.setLength(otherParams.getLength() - 1);
            //                    break;
            //            }
            ArrayList<Button> button = new ArrayList<>();
            //                button.add(new RedirectButton("web_url", "Buy @  " + product.getVariants().get(id).getPrice(), "http://" + page.getShopName() + ".myshopify.com/collections/" + collection.getHandle() + "/products/" + product.getHandle() + "?variant=" + product.getVariants().get(id).getId()));
            button.add(new RedirectButton("web_url", "Buy @  " + product.getVariants().get(id).getPrice(),
                    "http://" + page.getShopName() + ".myshopify.com/cart/"
                            + product.getVariants().get(id).getId() + ":1"));
            button.add(new PayloadButton("postback", "back", gson.toJson(otherParams)));
            button.add(new PayloadButton("postback", "home", gson.toJson(new ResponseModel(0, 0))));
            Element element = new Element();
            Variant variant = product.getVariants().get(id);
            if (product.getImages().size() > 0) {
                if (variant.getImageId() != 0) {
                    for (Image images : product.getImages()) {
                        if (images.getId() == variant.getImageId()) {
                            element.setImage_url(images.getSrc());
                            //                                            imageURL.add(images.getSrc());
                            break;
                        }
                    }
                } else {
                    element.setImage_url(product.getImages().get(0).getSrc());
                    //                                    imageURL.add(product.getImages().get(0).getSrc());
                }
            } else {
                //                    element.setImage_url(product.getImages().get(0).getSrc());
                //                                imageURL.add(null);
            }
            //                if (product.getImages().size() > 0) {
            //                    element.setImage_url(product.getImages().get(0).getSrc());
            //                }
            element.setButtons(button);
            element.setTitle(product.getTitle());
            element.setSubtitle("");

            elements.add(element);

            payload.setElements(elements);

            attachment.setPayload(payload);

            System.out.println("message generated");

            SendAttachmentMessage messageData = new SendAttachmentMessage(new Recipient(recepientID),
                    new SendAttachment(attachment));

            System.out.println(gson.toJson(messageData));

            AppConstant.ACCESSTOKEN = page.getAccessToken();

            if (!AppConstant.ACCESSTOKEN.isEmpty()) {
                RestClient.instance.getApiService().sendAttachmentToUser(messageData, new Callback<Response>() {

                    @Override
                    public void failure(RetrofitError re) {
                        System.err.println("something went wrong on facebook response");
                    }

                    @Override
                    public void success(Response response, Response rspns) {
                        System.out.println("facebook response: " + gson.toJson(rspns));
                    }
                });
            } else {
                System.out.println("ACCESS TOKEN should not be null");
            }
        } else {
            sendTextMessage(recepientID, "something went wrong!!! Please try again.:)", page);
        }
        //            sendTextMessage(recepientID, otherParams, page);
    } else {

        ArrayList<String> options = new ArrayList<>();
        ArrayList<String> imageURL = new ArrayList<>();

        switch (position) {
        case 2:
            for (Variant variant : product.getVariants()) {
                if (!options.contains(variant.getOption1())) {
                    options.add(variant.getOption1());
                    if (product.getImages().size() > 0) {
                        if (variant.getImageId() != 0) {
                            for (Image images : product.getImages()) {
                                if (images.getId() == variant.getImageId()) {
                                    imageURL.add(images.getSrc());
                                    break;
                                }
                            }
                        } else {
                            imageURL.add(product.getImages().get(0).getSrc());
                        }
                    } else {
                        imageURL.add(null);
                    }
                }
            }
            break;
        case 3: {
            String option1 = otherParams.getOption1();
            for (Variant variant : product.getVariants()) {
                if (!options.contains(variant.getOption2()) && variant.getOption1().equalsIgnoreCase(option1)) {
                    options.add(variant.getOption2());
                    System.out.println();
                    System.out.println();
                    System.out.println(gson.toJson(variant));
                    System.out.println();
                    System.out.println();
                    if (product.getImages().size() > 0) {
                        if (variant.getImageId() != 0) {
                            for (Image images : product.getImages()) {
                                if (images.getId() == variant.getImageId()) {
                                    imageURL.add(images.getSrc());
                                    break;
                                }
                            }
                        } else {
                            imageURL.add(product.getImages().get(0).getSrc());
                        }
                    } else {
                        imageURL.add(null);
                    }
                }
            }
            break;
        }
        case 4: {
            String option1 = otherParams.getOption1();
            String option2 = otherParams.getOption2();
            for (Variant variant : product.getVariants()) {
                if (!options.contains(variant.getOption3()) && variant.getOption1().equals(option1)
                        && variant.getOption2().equals(option2)) {
                    options.add(variant.getOption3());
                    if (product.getImages().size() > 0) {
                        if (variant.getImageId() != 0) {
                            for (Image images : product.getImages()) {
                                if (images.getId() == variant.getImageId()) {
                                    imageURL.add(images.getSrc());
                                    break;
                                }
                            }
                        } else {
                            imageURL.add(product.getImages().get(0).getSrc());
                        }
                    } else {
                        imageURL.add(null);
                    }
                }
            }
            break;
        }
        default:
            break;
        }

        //            for (Option option : product.getOptions()) {
        //                System.out.println("position : " + option.getPosition() + " selected: " + position);
        //                if (option.getPosition() == position - 1) {
        System.out.println("varient size: " + gson.toJson(options));
        for (int i = 0; i < options.size(); i++) {
            String value = options.get(i);
            switch (position - 1) {
            case 1:
                otherParams.setOption1(value);
                break;
            case 2:
                otherParams.setOption2(value);
                break;
            case 3:
                otherParams.setOption3(value);
                break;
            }
            otherParams.setLength(position + 1);
            ArrayList<Button> button = new ArrayList<>();
            button.add(new PayloadButton("postback", "" + value, gson.toJson(otherParams)));
            //                        switch (otherParams.getLength()) {
            //                            case 1:
            //                                otherParams.setOption1(null);
            //                                otherParams.setProductID(0);
            //                                break;
            //                            case 2:
            //                                otherParams.setOption1(null);
            //                                otherParams.setOption2(null);
            //                                otherParams.setLength(otherParams.getLength() - 1);
            //                                break;
            //                            case 3:
            //                                otherParams.setOption2(null);
            //                                otherParams.setOption3(null);
            //                                otherParams.setLength(otherParams.getLength() - 1);
            //                                break;
            //                        }
            //                    button.add(new RedirectButton("postback", "back", "back:" + otherParams));
            otherParams.setLength(position - 1);
            button.add(new PayloadButton("postback", "back", gson.toJson(otherParams)));
            button.add(new PayloadButton("postback", "home", gson.toJson(new ResponseModel(0, 0))));
            Element element = new Element();
            //                        if (product.getImages().size() > 0) {
            //                            element.setImage_url(product.getImages().get(0).getSrc());
            //                        }
            if (imageURL.get(i) != null) {
                element.setImage_url(imageURL.get(i));
            }
            element.setButtons(button);
            element.setTitle("Select " + product.getOptions().get(position - 2).getName());
            element.setSubtitle(product.getTitle());

            elements.add(element);

        }
        //                    otherParams.setLength(position - 1);
        //                    button.add(new PayloadButton("postback", "back", gson.toJson(otherParams)));
        //                    button.add(new PayloadButton("postback", "home", gson.toJson(new ResponseModel(0, 0))));
        //                    Element element = new Element();
        //                    if (product.getImages().size() > 0) {
        //                        element.setImage_url(product.getImages().get(0).getSrc());
        //                    }
        //                    element.setButtons(button);
        //                    element.setTitle("Select " + product.getOptions().get(position - 1).getName());
        //                    element.setSubtitle(product.getTitle());
        //
        //                    elements.add(element);
        //                    break;
        //                }
        //            }

        payload.setElements(elements);

        attachment.setPayload(payload);

        System.out.println("message generated");

        SendAttachmentMessage messageData = new SendAttachmentMessage(new Recipient(recepientID),
                new SendAttachment(attachment));

        System.out.println(gson.toJson(messageData));

        AppConstant.ACCESSTOKEN = page.getAccessToken();

        if (!AppConstant.ACCESSTOKEN.isEmpty()) {
            RestClient.instance.getApiService().sendAttachmentToUser(messageData, new Callback<Response>() {

                @Override
                public void failure(RetrofitError re) {
                    System.err.println("something went wrong on facebook response");
                }

                @Override
                public void success(Response response, Response rspns) {
                    System.out.println("facebook response: " + gson.toJson(rspns));
                }
            });
        } else {
            System.out.println("ACCESS TOKEN should not be null");
        }
    }
}

From source file:com.mlveda.dori.Webhook.java

private ArrayList<Product> getProducts(long collectionID) {
    MongoDatabase db = MongoProvider.getInstance();

    //        MongoCollection<Product> products = db.getCollection("disneytoys.myshopify.com_products", Product.class);
    System.out.println("collectionID: " + collectionID);

    FindIterable<Document> coll = db.getCollection("dakshal.myshopify.com_collects")
            .find(eq("collection_id", collectionID));

    final Type collectionType = new TypeToken<ArrayList<ProductCollectionMapping>>() {
    }.getType();/*from   w  w w  . ja v a2  s  .  c o m*/
    final Type productType = new TypeToken<ArrayList<Product>>() {
    }.getType();

    final ArrayList<ProductCollectionMapping> map = new ArrayList<>();
    final ArrayList<Product> products = new ArrayList<>();

    System.out.println();
    System.out.println("coll: " + coll.first());
    System.out.println();

    coll.forEach(new Block<Document>() {
        @Override
        public void apply(Document document) {
            map.add(gson.fromJson(gson.toJson(document), ProductCollectionMapping.class));
            //                System.out.println("document is: " + gson.toJson(document));
            //                ArrayList<ProductCollectionMapping> c = gson.fromJson(gson.toJson(document.get("collects")), collectionType);
            //                System.out.println(c);
            //                map.addAll(c);
            //                collection.add(t);
        }
    });

    System.out.println();
    System.out.println("map: " + map.size());
    System.out.println();

    for (ProductCollectionMapping pcm : map) {
        System.out.println("productID: " + pcm.getProductId());
        FindIterable<Document> prod = db.getCollection("dakshal.myshopify.com_products")
                .find(eq("id", pcm.getProductId()));
        System.out.println();
        System.out.println("prod: " + prod.toString());
        System.out.println();
        prod.forEach(new Block<Document>() {
            @Override
            public void apply(Document document) {
                Product prod = gson.fromJson(gson.toJson(document), Product.class);
                if (!products.contains(prod)) {
                    products.add(prod);
                }
                //                    System.out.println(gson.toJson(document));
                //                    ArrayList<Product> c = gson.fromJson(gson.toJson(document.get("collects")), productType);
                //                    System.out.println(c);
                //                    products.addAll(c);
                //                collection.add(t);
            }
        });
    }

    System.out.println();
    System.out.println();

    System.out.println("productlist: " + gson.toJson(products));

    return products;
}

From source file:com.mlveda.dori.Webhook.java

private Product getVarients(long productID) {
    MongoDatabase db = MongoProvider.getInstance();

    //        MongoCollection<Product> products = db.getCollection("disneytoys.myshopify.com_products", Product.class);
    System.out.println("collectionID: " + productID);

    System.out.println("productID: " + productID);
    FindIterable<Document> prod = db.getCollection("dakshal.myshopify.com_products").find(eq("id", productID));
    System.out.println();/*from  w w w.ja  v  a2s  .c  om*/
    System.out.println("prod: " + prod.toString());
    System.out.println();

    Product product = gson.fromJson(gson.toJson(prod.first()), Product.class);

    //        prod.forEach(new Block<Document>() {
    //            @Override
    //            public void apply(Document document) {
    //                Product prod = gson.fromJson(gson.toJson(document), Product.class
    //                );
    //                if (!products.contains(prod)) {
    //                    products.add(prod);
    //                }
    ////                    System.out.println(gson.toJson(document));
    ////                    ArrayList<Product> c = gson.fromJson(gson.toJson(document.get("collects")), productType);
    ////                    System.out.println(c);
    ////                    products.addAll(c);
    ////                collection.add(t);
    //            }
    //        });
    System.out.println();
    System.out.println();

    System.out.println("productlist: " + gson.toJson(product));

    return product;
}

From source file:com.mlveda.dori.Webhook.java

private PagesInsertData getStoreName(String storeId) {
    MongoDatabase db = MongoProvider.getInstance();

    FindIterable<Document> collection = db.getCollection("facebook_pages").find(eq("id", storeId));

    PagesInsertData facebookPage = gson.fromJson(gson.toJson(collection.first()), PagesInsertData.class);

    return facebookPage;
}

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);//from w ww . jav  a 2s  .  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();
}