Example usage for com.mongodb DBCollection insert

List of usage examples for com.mongodb DBCollection insert

Introduction

In this page you can find the example usage for com.mongodb DBCollection insert.

Prototype

public WriteResult insert(final List<? extends DBObject> documents) 

Source Link

Document

Insert documents into a collection.

Usage

From source file:brooklyn.entity.nosql.mongodb.MongoDBTestHelper.java

License:Apache License

/**
 * Inserts a new object with { key: value } at given server.
 * @return The new document's id/*from   w  w w  . j a va2s .c o  m*/
 */
public static String insert(AbstractMongoDBServer entity, String key, Object value) {
    LOG.info("Inserting {}:{} at {}", new Object[] { key, value, entity });
    MongoClient mongoClient = clientForServer(entity);
    try {
        DB db = mongoClient.getDB(TEST_DB);
        DBCollection testCollection = db.getCollection(TEST_COLLECTION);
        BasicDBObject doc = new BasicDBObject(key, value);
        testCollection.insert(doc);
        ObjectId id = (ObjectId) doc.get("_id");
        return id.toString();
    } finally {
        mongoClient.close();
    }
}

From source file:bruma.tools.Isis2Mongo.java

License:Open Source License

public static void main(final String[] args) {
    if (args.length < 3) {
        usage();/*from   ww  w.j  a v  a2 s .  com*/
    }

    String isisMaster = null;
    String mongoDbName = null;
    String mongoCollection = null;
    String host = "localhost";
    int port = DEFAULT_PORT;
    String user = null;
    String password = null;
    String encoding = Master.GUESS_ISO_IBM_ENCODING;
    int from = 1;
    int to = Integer.MAX_VALUE;
    int idTag = 0;
    int tell = Integer.MAX_VALUE;
    boolean useFDT = false;
    boolean useOnlyFDT = false;
    boolean clearCollection = false;

    for (String arg : args) {
        if (arg.startsWith("-isisMaster=")) {
            isisMaster = arg.substring(12);
        } else if (arg.startsWith("-mongoDbName=")) {
            mongoDbName = arg.substring(13);
        } else if (arg.startsWith("-collection=")) {
            mongoCollection = arg.substring(12);
        } else if (arg.startsWith("-mongoHost=")) {
            host = arg.substring(11);
        } else if (arg.startsWith("-mongoPort=")) {
            port = Integer.parseInt(arg.substring(11));
        } else if (arg.startsWith("-user=")) {
            user = arg.substring(6);
        } else if (arg.startsWith("-password=")) {
            password = arg.substring(10);
        } else if (arg.startsWith("-encod=")) {
            encoding = arg.substring(7);
        } else if (arg.startsWith("-from=")) {
            from = Integer.parseInt(arg.substring(6));
        } else if (arg.startsWith("-to=")) {
            to = Integer.parseInt(arg.substring(4));
        } else if (arg.startsWith("-idTag=")) {
            idTag = Integer.parseInt(arg.substring(7));
        } else if (arg.startsWith("-tell=")) {
            tell = Integer.parseInt(arg.substring(6));
        } else if (arg.equals("--useFDT")) {
            useFDT = true;
        } else if (arg.equals("--useOnlyFDT")) {
            useOnlyFDT = true;
        } else if (arg.equals("--clearCollection")) {
            clearCollection = true;
        } else {
            usage();
        }
    }

    final Logger log = Logger.getLogger("Isis2Mongo");
    final List<DBObject> buffer = new ArrayList<DBObject>();

    try {
        final DB database = getDatabase(host, port, user, password, mongoDbName);
        final DBCollection collection = database.getCollection(mongoCollection);
        final Master mst = MasterFactory.getInstance(isisMaster).setEncoding(encoding).open();
        final boolean hasFdt = new File(Util.changeFileExtension(isisMaster, ZeFDT.DEFAULT_EXTENSION)).isFile();
        final ZeFDT fdt = ((useFDT || useOnlyFDT) && hasFdt) ? new ZeFDT().fromFile(isisMaster) : null;
        final Map<Integer, ZeFDT.ZeFDTField> mfdt = (fdt == null) ? null : fdt.getFieldDescriptionMapEx();

        to = Math.min(to, mst.getControlRecord().getNxtmfn() - 1);
        int cur = 0;

        if (clearCollection) {
            collection.drop();
        }

        for (int mfn = from; mfn <= to; mfn++) {
            final Record rec = mst.getRecord(mfn);

            if (rec.getStatus() == Record.Status.ACTIVE) {
                buffer.add(createDocument(rec, idTag, mfdt, useOnlyFDT));
                if (buffer.size() == DEFAULT_BUFFER_SIZE) {
                    final String errMess = collection.insert(buffer).getError();
                    if (errMess != null) {
                        log.warning(errMess);
                    }
                    buffer.clear();
                }
            }

            if (++cur == tell) {
                cur = 0;
                log.info("+++ " + Integer.toString(mfn));
            }
        }
        if (!buffer.isEmpty()) {
            final String errMess = collection.insert(buffer).getError();
            if (errMess != null) {
                log.warning(errMess);
            }
        }

        mst.close();
        log.info("Importing ");
        log.info(args[0]);
        log.info(" finished.");
        log.info("Documents imported: ");
        log.info(Integer.toString(cur));
        log.info("Total documents : ");
        log.info(Long.toString(collection.count()));
    } catch (Exception ex) {
        log.severe(ex.getMessage());
    }
}

From source file:BusinessLogic.Service.RestaurantService.java

public String addRestaurant(Restaurant rs) {
    //String name, String direccion, String phone) 
    String name = rs.getName();/*www .  java 2 s  .co m*/
    String direccion = rs.getAddress();
    String phone = rs.getPhone();
    String restaurantCreate = null;

    try {
        // To connect to mongo dbserver
        MongoConnection dbSingleton = MongoConnection.getInstance();
        DB db = dbSingleton.getTestdb();
        DBCollection coll = db.getCollection(collName);

        System.out.println("Collection restaurants selected successfully");

        BasicDBObject doc = new BasicDBObject("name", name).append("direccion", direccion).append("phone",
                phone);
        coll.insert(doc);
        System.out.println("Document inserted successfully");
        restaurantCreate = "Success";

    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }

    if (restaurantCreate != null) {
        return "The restaurant has been created successfully!";
    } else {
        return "The restaurant has not been created!";
    }

}

From source file:BusinessLogic.Service.RestaurantService.java

public String addRestaurant(String name, String direccion, String phone) {
    String restaurantCreate = null;

    try {//  ww  w.j  a v  a  2s .co m
        // To connect to mongo dbserver
        MongoConnection dbSingleton = MongoConnection.getInstance();
        DB db = dbSingleton.getTestdb();
        DBCollection coll = db.getCollection(collName);

        System.out.println("Collection restaurants selected successfully");

        BasicDBObject doc = new BasicDBObject("name", name).append("direccion", direccion).append("phone",
                phone);
        coll.insert(doc);
        System.out.println("Document inserted successfully");
        restaurantCreate = "Success";

    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }

    if (restaurantCreate != null) {
        return "The restaurant has been created successfully!";
    } else {
        return "The restaurant has not been created!";
    }
}

From source file:buysell.sign.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:

    try {//w  w  w.  j a v  a  2  s . c  o m
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        DB db = mongoClient.getDB("snehal");
        System.out.println("Connect to database successfully");
        DBCollection coll = db.getCollection("user");
        System.out.println("Collection created successfully");
        String fullname = jTextField2.getText().toString();

        String email = jTextField3.getText().toString();
        String passwd = jTextField4.getText().toString();
        System.out.println("finalproject.sign.jButton1ActionPerformed()" + fullname);
        if (jTextField2.getText().length() != 0 && jTextField3.getText().length() != 0
                && jTextField4.getText().length() != 0) {
            BasicDBObject doc = new BasicDBObject("name", fullname).

                    append("passwd", passwd);

            coll.insert(doc);

            System.out.println("Document inserted successfully");
            home h1 = new home();
            h1.setVisible(true);
            dispose();
        } else {
            JOptionPane.showMessageDialog(null, "Fill every field");
        }
    } catch (NumberFormatException e) {
        System.out.println();
    }
}

From source file:buysell.subads.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    try {//from   w ww  .ja  v a 2s . c  o m
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        DB db = mongoClient.getDB("buysale");
        System.out.println("Connect to database successfully");
        DBCollection coll = db.getCollection("assetes");
        System.out.println("Collection created successfully");
        String name = jTextField1.getText().toString();
        String email = jTextField2.getText().toString();
        String phoneno = jTextField3.getText().toString();
        String price = jTextField4.getText().toString();
        String photourl = jTextField5.getText().toString();
        String type = jComboBox1.getSelectedItem().toString();
        DB dB = mongoClient.getDB("snehal");
        System.out.println("Connect to database successfully");
        DBCollection colle = dB.getCollection("user");
        System.out.println("Collection created successfully");
        String uname = jTextField6.getText().toString();
        String passwd = jPasswordField1.getText().toString();
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("name", uname);
        searchQuery.put("passwd", passwd);

        DBCursor cursor = colle.find(searchQuery);
        int i = 0;
        while (cursor.hasNext()) {
            i = 1;
            System.out.println(cursor.next());
        }
        if (i == 0) {
            JOptionPane.showMessageDialog(null, "user name or passwod is wrong");

        } else {
            if (jTextField2.getText().length() != 0 && jTextField3.getText().length() != 0
                    && jTextField4.getText().length() != 0 && jTextField1.getText().length() != 0
                    && jTextField5.getText().length() != 0) {

                BasicDBObject doc = new BasicDBObject("name", name).append("username", uname)
                        .append("passwd", passwd).append("email", email).append("phoneno", phoneno)
                        .append("price", price).append("type", type).append("photourl", photourl);

                coll.insert(doc);
                home h2 = new home();
                h2.setVisible(true);
                dispose();
                System.out.println("Document inserted successfully");
            } else {
                JOptionPane.showMessageDialog(null, "enter the every field");
            }
        }

    } catch (NumberFormatException e) {
        System.out.println();
    }
}

From source file:cfel.servlet.ServiceServlet.java

License:Open Source License

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)// w  w w. j  a v a  2 s.  co  m
 * 
 *      Insert a new resource
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String type = request.getParameter("type");
    String id = request.getParameter("id");
    String data = request.getParameter("data");
    System.out.println("doPost: type=" + type + " id=" + id + " data=" + data);

    if ("file".equals(type)) {
        // Save a file with id
        doPut(request, response);
        return;
    }

    DBCollection collection = mDS.getCollection(type);
    if (collection == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, String.format("Unknown collection %s", type));
        return;
    }

    String action = request.getParameter("action");
    if (action != null) {
        // Manipulate database
        if ("update".equals(action)) {
            String query = request.getParameter("query");
            String update = request.getParameter("update");
            String upsert = request.getParameter("upsert");
            String multi = request.getParameter("multi");
            DBObject queryObj = null;
            if (id != null) {
                queryObj = new BasicDBObject("_id", new ObjectId(id));
            } else if (query != null) {
                queryObj = (DBObject) JSON.parse(query);
            }
            DBObject updateObj = update != null ? (DBObject) JSON.parse(update) : null;
            if (queryObj == null || updateObj == null) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No query or update parameters");
                return;
            }
            sendJSON(collection.update(queryObj, updateObj, "true".equals(upsert), "true".equals(multi)),
                    response);
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, String.format("Unknown action %s", action));
        }
        return;
    }

    if (data == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No data specified");
        return;
    }

    // Insert a document
    DBObject dataObject = (DBObject) JSON.parse(data);
    Object dataID = dataObject.get("_id");
    if (dataID != null && collection.findOne(dataID) != null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Duplicated id");
        return;
    }
    collection.insert(dataObject);
    sendJSON(dataObject, response);
}

From source file:ch.windmobile.server.social.mongodb.ChatServiceImpl.java

License:Open Source License

@Override
public Message postMessage(String chatRoomId, String pseudo, String text, String emailHash) {
    String collectionName = computeCollectionName(chatRoomId);
    DBCollection col = getOrCreateCappedCollection(collectionName);

    DBObject chatItem = new BasicDBObject();
    Double id = (Double) db.eval(counter, chatRoomId);
    chatItem.put("_id", id.longValue());
    chatItem.put(MongoDBConstants.CHAT_PROP_TEXT, text);
    chatItem.put(MongoDBConstants.CHAT_PROP_USER, pseudo);
    DateTime date = new DateTime().toDateTimeISO();
    chatItem.put(MongoDBConstants.CHAT_PROP_TIME, date.toString());
    chatItem.put(MongoDBConstants.CHAT_PROP_EMAIL_HASH, emailHash);
    col.insert(chatItem);

    Message message = new Message();
    message.setId(id.toString());//w  w  w  .j  av a  2  s  .c om
    message.setDate(date);
    message.setPseudo(pseudo);
    message.setText(text);
    message.setEmailHash(emailHash);

    return message;
}

From source file:cn.edu.hfut.dmic.webcollector.example.DemoSelenium.java

License:Open Source License

public static void main(String[] args) throws Exception {
    Executor executor = new Executor() {
        @Override//from   w ww  .  jav  a  2 s.c om
        public void execute(CrawlDatum datum, CrawlDatums next) throws Exception {
            MongoClient mongoClient = new MongoClient("localhost", 27017);
            // ?
            // DBCollection dbCollection = mongoClient.getDB("maoyan_crawler").getCollection("rankings_am"); 
            DB db = mongoClient.getDB("maoyan_crawler");
            // ?????
            Set<String> colls = db.getCollectionNames();
            for (String s : colls) {
                // Collection(?"")
                if (s.equals("attend_rate")) {
                    db.getCollection(s).drop();
                }
            }
            DBCollection dbCollection = db.getCollection("attend_rate");
            HtmlUnitDriver driver = new HtmlUnitDriver();
            driver.setJavascriptEnabled(false);
            driver.get(datum.getUrl());
            System.out.println(driver.getPageSource());
            WebElement click_view = driver.findElement(By.xpath("//div[@id='seatContent']//span[1]"));
            click_view.click();
            String gold_seat = driver.getWindowHandle();
            driver.switchTo().window(gold_seat);
            System.out.println(driver.getPageSource());
            WebElement city_name = driver.findElement(By.xpath("//*[@id='all-citys']/div[1]/ul/li[1]/a"));
            System.out.println(city_name.getText());
            WebElement element = driver.findElementByCssSelector("div#seat_table");
            List<WebElement> movie_name = element.findElements(By.className("c1 lineDot"));
            List<WebElement> boxoffice_rate = element.findElements(By.className("c2 red"));
            List<WebElement> visit_pershow = element.findElements(By.className("c3 gray"));
            WebElement cityarea = driver.findElementByCssSelector("span[class='today']");
            System.out.println(cityarea.getText());
            for (int i = 0; i < movie_name.size(); i++) {
                System.out.println(movie_name.get(i).getText());
                System.out.println(boxoffice_rate.get(i).getText());
                System.out.println(visit_pershow.get(i).getText());
                BasicDBObject dbObject = new BasicDBObject();
                dbObject.append("title", cityarea.getText()).append("movie_name", movie_name.get(i).getText())
                        .append("boxoffice_rate", boxoffice_rate.get(i).getText())
                        .append("visit_pershow", visit_pershow.get(i).getText());
                dbCollection.insert(dbObject);
            }
            mongoClient.close();
        }
    };

    //DBDBManager
    DBManager manager = new BerkeleyDBManager("crawl");
    //Crawler?DBManagerExecutor
    Crawler crawler = new Crawler(manager, executor);
    crawler.addSeed("http://pf.maoyan.com/attend/rate");
    crawler.start(1);
}

From source file:cn.edu.hfut.dmic.webcollector.example.FirefoxSelenium3.java

License:Open Source License

public static void main(String[] args) throws Exception {
    Executor executor = new Executor() {
        @Override/*from  w  w  w  .  jav  a 2s .  c  o m*/
        public void execute(CrawlDatum datum, CrawlDatums next) throws Exception {
            MongoClient mongoClient = new MongoClient("localhost", 27017);
            // ?
            // DBCollection dbCollection = mongoClient.getDB("maoyan_crawler").getCollection("rankings_am"); 
            DB db = mongoClient.getDB("maoyan_crawler");
            // ?????
            Set<String> colls = db.getCollectionNames();
            for (String s : colls) {
                // Collection(?"")
                if (s.equals("attend_rate")) {
                    db.getCollection(s).drop();
                }
            }
            DBCollection dbCollection = db.getCollection("attend_rate");
            ProfilesIni pi = new ProfilesIni();
            FirefoxProfile profile = pi.getProfile("default");
            WebDriver driver = new FirefoxDriver(profile);
            driver.manage().window().maximize();
            driver.manage().timeouts().pageLoadTimeout(3, TimeUnit.SECONDS);
            //                driver.setJavascriptEnabled(false);
            driver.get(datum.getUrl());
            //                System.out.println(driver.getPageSource());
            driver.findElement(By.xpath("//*[@id='seat_city']")).click();
            driver.switchTo().window(driver.getWindowHandle());

            int city_num = driver.findElements(By.xpath("//div[@id='all-citys']/div/ul/li/a")).size();
            for (int i = 0; i < city_num; i++) {
                System.out.println("A city chosen" + i);
                System.out.println(
                        driver.findElements(By.xpath("//div[@id='all-citys']/div/ul/li/a")).get(i).getText());
                String city = driver.findElements(By.xpath("//div[@id='all-citys']/div/ul/li/a")).get(i)
                        .getText();
                ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);",
                        driver.findElements(By.xpath("//div[@id='all-citys']/div/ul/li/a")).get(i));
                ((JavascriptExecutor) driver).executeScript("window.scrollBy(0, -250)", "");
                Thread.sleep(1000);
                new Actions(driver)
                        .moveToElement(
                                driver.findElements(By.xpath("//div[@id='all-citys']/div/ul/li/a")).get(i))
                        .click().perform();
                driver.switchTo().window(driver.getWindowHandle());
                //                System.out.println(driver.findElement(By.xpath("//span[@class='today']/em")).getText());
                System.out.println(driver.findElement(By.xpath("//span[@class='today']")).getText());
                for (int j = 0; j < driver
                        .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c1 lineDot']"))
                        .size(); j++) {
                    System.out.println(driver
                            .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c1 lineDot']"))
                            .get(j).getText());
                    System.out.println(
                            driver.findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c2 red']"))
                                    .get(j).getText());
                    System.out.println(
                            driver.findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c3 gray']"))
                                    .get(j).getText());
                    BasicDBObject dbObject = new BasicDBObject();
                    dbObject.append("title", driver.findElement(By.xpath("//span[@class='today']")).getText())
                            .append("city", city)
                            .append("mov_cnname",
                                    driver.findElements(
                                            By.xpath("//div[@id='seat_table']//ul//li[@class='c1 lineDot']"))
                                            .get(j).getText())
                            .append("boxoffice_rate", driver
                                    .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c2 red']"))
                                    .get(j).getText())
                            .append("visit_pershow", driver
                                    .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c3 gray']"))
                                    .get(j).getText());
                    dbCollection.insert(dbObject);
                }
                System.out.println("new city list to choose");
                new Actions(driver).moveToElement(driver.findElement(By.xpath("//*[@id='seat_city']"))).click()
                        .perform();
                driver.switchTo().window(driver.getWindowHandle());
                Thread.sleep(500);
            }
            driver.close();
            driver.quit();
            mongoClient.close();
        }
    };

    //DBDBManager
    DBManager manager = new BerkeleyDBManager("crawl");
    //Crawler?DBManagerExecutor
    Crawler crawler = new Crawler(manager, executor);
    crawler.addSeed("http://pf.maoyan.com/attend/rate");
    crawler.start(1);
}