Example usage for com.mongodb.client MongoCollection insertOne

List of usage examples for com.mongodb.client MongoCollection insertOne

Introduction

In this page you can find the example usage for com.mongodb.client MongoCollection insertOne.

Prototype

void insertOne(TDocument document);

Source Link

Document

Inserts the provided document.

Usage

From source file:pt.ua.cbd.cbd_project.service.BookServiceMongo.java

public Book addNewBook(Book book) {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("authors", book.getAuthorsArray());
    jsonObject.put("id", book.getId());
    jsonObject.put("title", book.getTitle());
    jsonObject.put("addToLibraryDate", book.getAddToLibraryDate());

    String jsonFormattedString = jsonObject.toString().replaceAll("\\\\", "");
    BasicDBObject dbObject = (BasicDBObject.parse(jsonFormattedString));
    MongoCollection<BasicDBObject> coll = db.getCollection("book", BasicDBObject.class);
    coll.insertOne(dbObject);
    return book;//www  .  j  a  v  a  2s. c  om
}

From source file:result.analysis.Dbops.java

void CreateDb(String name) {

    try {//w  ww  .j a  v a2  s.c o m

        // To connect to mongodb server
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // Now connect to your databases
        MongoDatabase db = mongoClient.getDatabase(name);//must be there where csvparser is invoked
        System.out.println("Connect to database successfully");
        MongoCollection<Document> collection = db.getCollection("test");
        Document doc = new Document("name", "MongoDB").append("type", "database").append("count", 1)
                .append("info", new Document("x", 203).append("y", 102));
        collection.insertOne(doc);

        System.out.println(collection.count());
        Document myDoc = collection.find().first();
        System.out.println(myDoc.toJson());

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

}

From source file:rmteles.learning.mongodb.examples.week2.spark.HelloWorldMongoDBSparkFreemarkerStyle.java

License:Apache License

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

    MongoClient client = new MongoClient(new ServerAddress("localhost", 27017));

    MongoDatabase database = client.getDatabase("course");
    final MongoCollection<Document> collection = database.getCollection("hello");
    collection.drop();/*  w  w w . ja v  a2 s.  c  o m*/

    collection.insertOne(new Document("name", "MongoDB"));

    Spark.get("/", (request, response) -> {
        StringWriter writer = new StringWriter();
        try {
            Template helloTemplate = configuration.getTemplate("hello.ftl");

            Document document = collection.find().first();

            helloTemplate.process(document, writer);
        } catch (Exception e) {
            Spark.halt(500);
            e.printStackTrace();
        }
        return writer;
    });
}

From source file:rocks.teammolise.myunimol.webapp.issues.SendAdvice.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w w  w.  j  a v a  2s .  c o  m*/
 * 
 * @param request
 *            servlet request
 * @param response
 *            servlet response
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();

    MongoClient mongoClient = null;
    try {
        if (request.getSession().getAttribute("userInfo") == null) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            return;
        }

        UserInfo userInfo = (UserInfo) request.getSession().getAttribute("userInfo");

        String username = userInfo.getUsername();
        String password = userInfo.getPassword();

        String type = request.getParameter("type");
        String other = request.getParameter("other");
        String details = request.getParameter("details");

        ConfigurationManager confMgr = ConfigurationManagerHandler.getInstance();
        String mdburi = confMgr.getMongoDbUri();
        int pos = mdburi.lastIndexOf("/");
        String dbName = mdburi.substring(pos + 1, mdburi.length());
        MongoClientURI uri = new MongoClientURI(mdburi);
        mongoClient = new MongoClient(uri);
        MongoDatabase db = mongoClient.getDatabase(dbName);

        MongoCollection<Document> collection = db.getCollection("advices");
        Map<String, Object> userinfo = new HashMap<String, Object>();
        userinfo.put("name", userInfo.getName());
        userinfo.put("surname", userInfo.getSurname());
        userinfo.put("course", userInfo.getCourse());
        userinfo.put("department", userInfo.getDepartment());
        userinfo.put("totalCFU", userInfo.getTotalCFU());
        userinfo.put("username", userInfo.getUsername());
        userinfo.put("studentId", userInfo.getStudentId());
        userinfo.put("enrolledExams", userInfo.getEnrolledExams());
        userinfo.put("registrationDate", userInfo.getRegistrationDate());
        userinfo.put("studentClass", userInfo.getStudentClass());
        userinfo.put("coursePath", userInfo.getCoursePath());
        userinfo.put("courseLength", userInfo.getCourseLength());
        Document userInfoDoc = new Document(userinfo);
        Map<String, Object> advice = new HashMap<String, Object>();
        advice.put("type", type);
        if (other != null)
            advice.put("other", other);
        advice.put("details", details);
        advice.put("userInfo", userInfoDoc);
        collection.insertOne(new Document(advice));

        out.println("{\"result\":\"success\"}");
    } catch (Exception ex) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
    } finally {
        out.close();
        mongoClient.close();
    }
}

From source file:rocks.teammolise.myunimol.webapp.issues.SendProblem.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w w w .ja  v  a2s . c om
 * 
 * @param request
 *            servlet request
 * @param response
 *            servlet response
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();

    MongoClient mongoClient = null;
    try {
        if (request.getSession().getAttribute("userInfo") == null) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            return;
        }

        UserInfo userInfo = (UserInfo) request.getSession().getAttribute("userInfo");

        String username = userInfo.getUsername();
        String password = userInfo.getPassword();

        String type = request.getParameter("type");
        String other = request.getParameter("other");
        String details = request.getParameter("details");

        ConfigurationManager confMgr = ConfigurationManagerHandler.getInstance();
        String mdburi = confMgr.getMongoDbUri();
        int pos = mdburi.lastIndexOf("/");
        String dbName = mdburi.substring(pos + 1, mdburi.length());
        MongoClientURI uri = new MongoClientURI(mdburi);
        mongoClient = new MongoClient(uri);
        MongoDatabase db = mongoClient.getDatabase(dbName);

        MongoCollection<Document> collection = db.getCollection("problems");
        Map<String, Object> userinfo = new HashMap<String, Object>();
        userinfo.put("name", userInfo.getName());
        userinfo.put("surname", userInfo.getSurname());
        userinfo.put("course", userInfo.getCourse());
        userinfo.put("department", userInfo.getDepartment());
        userinfo.put("totalCFU", userInfo.getTotalCFU());
        userinfo.put("username", userInfo.getUsername());
        userinfo.put("studentId", userInfo.getStudentId());
        userinfo.put("enrolledExams", userInfo.getEnrolledExams());
        userinfo.put("registrationDate", userInfo.getRegistrationDate());
        userinfo.put("studentClass", userInfo.getStudentClass());
        userinfo.put("coursePath", userInfo.getCoursePath());
        userinfo.put("courseLength", userInfo.getCourseLength());
        Document userInfoDoc = new Document(userinfo);
        Map<String, Object> problem = new HashMap<String, Object>();
        problem.put("type", type);
        if (other != null)
            problem.put("other", other);
        problem.put("details", details);
        problem.put("userInfo", userInfoDoc);
        collection.insertOne(new Document(problem));

        out.println("{\"result\":\"success\"}");
    } catch (Exception ex) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
    } finally {
        out.close();
    }
}

From source file:swm.project.loadDataToDb.LoadDataToDb.java

/**
 * Call this function to load user data from u.data in db
 *//*from  w w w .  j  a  va  2  s  . c  om*/
public void loadUserDataToDb() throws NullPointerException {
    MongoCollection<Document> collection;
    collection = db.getCollection(Consts.UDATA);
    collection.dropCollection();
    db.createCollection(Consts.UDATA);

    FileInputStream fis = null;
    BufferedReader br;
    BufferedInputStream bis = null;
    try {
        fis = new FileInputStream("datafiles//u.data");
        br = new BufferedReader(new InputStreamReader(fis));
        String inputLine;

        while ((inputLine = br.readLine()) != null) {
            String[] fields = inputLine.split("\t");
            // System.out.println(fields[0]);
            Document d = new Document();
            d.put("userid", Integer.parseInt(fields[0]));
            d.put("itemid", Integer.parseInt(fields[1]));
            d.put("rating", Integer.parseInt(fields[2]));
            d.put("timestamp", fields[3]);
            collection.insertOne(d);
        }
    } catch (FileNotFoundException ex) {
        System.out.println("u.data file not found" + ex.getMessage());
    } catch (IOException ex) {
        System.out.println("u.data IO exception" + ex.getMessage());
    }
}

From source file:swm.project.loadDataToDb.LoadDataToDb.java

private void addDirectors(int id, List<String> director, MongoCollection<Document> movieNamesCollection) {
    Document d = new Document();
    d.put("_id", id);
    d.put(Consts.MOVIE_DIRECTORS_DATA, director);
    movieNamesCollection.insertOne(d);
}

From source file:swm.project.loadDataToDb.LoadDataToDb.java

private void addMovieDates(int id, int date, MongoCollection<Document> movieDatesCollection) {
    Document d = new Document();
    d.put("_id", id);
    d.put(Consts.MOVIE_DATE_DATA, date);
    movieDatesCollection.insertOne(d);
}

From source file:swm.project.loadDataToDb.LoadDataToDb.java

private void addMovieNames(int id, String movieName, MongoCollection<Document> movieNamesCollection) {
    Document d = new Document();
    d.put("_id", id);
    d.put(Consts.MOVIE_NAME_FIELD, movieName);
    movieNamesCollection.insertOne(d);
}

From source file:swm.project.loadDataToDb.LoadDataToDb.java

private void addMovieActors(int id, List<String> actors, MongoCollection<Document> movieNamesCollection) {
    Document d = new Document();
    d.put("_id", id);
    d.put(Consts.MOVIE_ACTORS_FIELD, actors);
    movieNamesCollection.insertOne(d);
}