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:gMIRC_handler.java

/**
 * Add a user to a channel (can check if the channel is a new channel)
 *
 * @param Username/*from   w  w w .  j a  va2  s .  co m*/
 * @param Channel
 * @return code
 */
private int AddChannel(String Username, String Channel) {
    int ret = 0;
    try {

        MongoClient mongoClient = new MongoClient();
        DB db = mongoClient.getDB("mirc");
        DBCollection coll = db.getCollection("channelCollection");
        BasicDBObject query = new BasicDBObject("username", Username).append("channel", Channel);

        DBCursor cursor = coll.find(query);

        try {
            if (cursor.hasNext()) {
                ret = 1;
                System.err.println(Username + " has joined Channel : " + Channel + "!");
            } else {
                query = new BasicDBObject("channel", Channel);
                DBCursor cursor2 = coll.find(query);
                try {
                    if (!cursor2.hasNext()) {
                        ret = 2;
                    }
                } finally {
                    cursor2.close();
                }
                BasicDBObject doc = new BasicDBObject("username", Username).append("channel", Channel);
                coll.insert(doc);
                System.out.println(Username + " joined Channel : " + Channel);
            }
        } finally {
            cursor.close();
        }

    } catch (UnknownHostException ex) {
        Logger.getLogger(gMIRC_handler.class.getName()).log(Level.SEVERE, null, ex);
    }
    return ret;
}

From source file:gMIRC_handler.java

/**
 * Register a user to the server (used in RegUser)
 *
 * @param username/*from ww w  . j a v a 2 s.c  o  m*/
 * @return code
 */
private int AddUser(String username) {
    int ret = 0;
    try {

        MongoClient mongoClient = new MongoClient();
        DB db = mongoClient.getDB("mirc");
        DBCollection coll = db.getCollection("activeUser");
        BasicDBObject query = new BasicDBObject("username", username);

        DBCursor cursor = coll.find(query);

        try {
            if (cursor.hasNext()) {
                Date now = new Date();
                long timestamp_now = now.getTime();
                long treshold = timestamp_now - (1000 * 10); //10
                BasicDBObject temp = (BasicDBObject) cursor.next();
                Date time_temp = (Date) temp.get("timestamp");
                long timestamp_temp = time_temp.getTime();
                if (timestamp_temp < treshold) {
                    ret = 2;
                    System.out.println(username + " has joined back!");
                } else {
                    ret = 1;
                    System.err.println(username + " has been used !");
                }
            } else {
                java.util.Date date = new java.util.Date();
                BasicDBObject doc = new BasicDBObject("username", username).append("timestamp", date);
                coll.insert(doc);
                System.out.println(username + " online !");
            }
        } finally {
            cursor.close();
        }

    } catch (UnknownHostException ex) {
        Logger.getLogger(gMIRC_handler.class.getName()).log(Level.SEVERE, null, ex);
    }
    return ret;
}

From source file:gMIRC_handler.java

private int UpdateLastActive(String username) {
    int ret = 0;//from   w ww  .  j av  a  2  s  . com
    try {

        MongoClient mongoClient = new MongoClient();
        DB db = mongoClient.getDB("mirc");
        DBCollection coll = db.getCollection("activeUser");
        BasicDBObject query = new BasicDBObject("username", username);

        DBCursor cursor = coll.find(query);

        try {
            if (cursor.hasNext()) {
                DBObject temp = cursor.next();
                java.util.Date date = new java.util.Date();
                temp.put("timestamp", date);
                coll.save(temp);
            } else {
                java.util.Date date = new java.util.Date();
                BasicDBObject doc = new BasicDBObject("username", username).append("timestamp", date);
                coll.insert(doc);
                System.out.println(username + " online !");
            }
        } finally {
            cursor.close();
        }

    } catch (UnknownHostException ex) {
        Logger.getLogger(gMIRC_handler.class.getName()).log(Level.SEVERE, null, ex);
    }
    return 0;
}

From source file:gMIRC_handler.java

/**
 * Moved active user to a passive user (soon to be deleted)
 *
 * @param username//ww w . ja v a2s. c o m
 * @return code
 */
public static int SoftDelete(String username) {
    int ret = 0;
    try {
        MongoClient mongoClient = new MongoClient();
        DB db = mongoClient.getDB("mirc");
        DBCollection coll = db.getCollection("activeUser");
        DBCollection coll2 = db.getCollection("passiveUser");
        BasicDBObject query = new BasicDBObject("username", username);

        DBCursor cursor = coll.find(query);

        try {
            if (cursor.hasNext()) {
                DBObject temp = cursor.next();
                coll2.insert(temp);
                coll.remove(temp);
            } else {
                ret = 1;
            }
        } finally {
            cursor.close();
        }
    } catch (UnknownHostException ex) {
        Logger.getLogger(gMIRC_handler.class.getName()).log(Level.SEVERE, null, ex);
    }
    return ret;
}

From source file:gMIRC_handler.java

private int PutMessage(String username, String channelname, String msg) {
    int ret = 0;//from  w w  w .  j av a2  s  .  c  om
    try {
        MongoClient mongoClient = new MongoClient();
        DB db = mongoClient.getDB("mirc");
        DBCollection coll = db.getCollection("inbox");
        DBCollection coll2 = db.getCollection("channelCollection");
        BasicDBObject query2 = new BasicDBObject("channel", channelname);
        BasicDBObject query = new BasicDBObject("channel", channelname).append("username", username);
        DBCursor cursor = coll2.find(query);
        try {
            if (cursor.hasNext()) {
                DBCursor cursor2 = coll2.find(query2);
                System.out.println("Got message from " + username);
                try {
                    java.util.Date date = new java.util.Date();
                    while (cursor2.hasNext()) {
                        ret = 1;
                        BasicDBObject temp = (BasicDBObject) cursor2.next();
                        String target = temp.get("username").toString();
                        BasicDBObject put = new BasicDBObject("target", target).append("username", username)
                                .append("channel", channelname).append("message", msg)
                                .append("timestamp", date.getTime());
                        coll.insert(put);
                        ret = 0;
                    }
                } finally {
                    cursor2.close();
                }
            } else {
                ret = 2;
                System.out.println(username + " not registered to Channel : " + channelname);
            }
        } finally {
            cursor.close();
        }

    } catch (UnknownHostException ex) {
        ret = 1;
        Logger.getLogger(gMIRC_handler.class.getName()).log(Level.SEVERE, null, ex);
    }
    return ret;
}

From source file:RequestHandler.java

public void insert(HttpServletRequest request) {
    DB db = mongo.getDB("test");
    DBCollection dbc = db.getCollection(collection);
    BasicDBObject add = new BasicDBObject();

    for (Map.Entry<String, String> ent : this.document.entrySet()) {
        add.append(ent.getKey(), request.getParameter(ent.getValue()));
    }//  ww w . jav a  2 s  .com
    dbc.insert(add);
    System.out.print(add);

}

From source file:ImportCSVtoMongo.java

public void run() {
    String csvFile = "";

    BufferedReader br = null;//  w w  w  . ja va  2s .c  o m

    String line = "";

    String csvSplitBy = "##";

    Scanner io = new Scanner(System.in);

    int i = 1;
    try {
        MongoClient mongo = new MongoClient("localhost", 27017);
        DB db = mongo.getDB("doep");
        //
        System.out.println("Enter the csv file path");
        csvFile = io.next();

        System.out.println("Enter the collection name you want to create");
        String coll_name = io.next();

        db.createCollection(coll_name, null);

        DBCollection coll = db.getCollection(coll_name);
        System.out.println("Connected to Collection");

        BasicDBObject doc = new BasicDBObject();

        br = new BufferedReader(new FileReader(csvFile));

        int q_no = 1;
        while ((line = br.readLine()) != null) {

            //use comma seperated values
            String[] question = line.split(csvSplitBy);
            System.out.println(i++);
            System.out.println("Question:" + question[1]);
            System.out.println("Option1:" + question[2]);
            System.out.println("Option2:" + question[3]);
            System.out.println("Option3:" + question[4]);
            System.out.println("Option4:" + question[5]);
            System.out.println("ANSWER: " + question[6]);
            System.out.println();

            doc.put("qid", coll_name + q_no);
            doc.put("quest", question[1]);
            doc.put("op1", question[2]);
            doc.put("op2", question[3]);
            doc.put("op3", question[4]);
            doc.put("op4", question[5]);
            doc.put("ans", question[6]);
            doc.put("image", "none");

            coll.insert(doc);
            q_no++;
            doc.clear();

        }
    } catch (UnknownHostException ex) {
        Logger.getLogger(ImportCSVtoMongo.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileNotFoundException e) {

    } catch (IOException e) {

    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

From source file:Veehicle_entry.java

public int validate(DBCollection coll, BasicDBObject dc) {

    if (checkLetters()) {
        if (checkNumbers()) {
            if (checkPassingCode()) {
                if (checkVehno()) {
                    coll.insert(dc);
                    JOptionPane.showMessageDialog(null, "Token Generated !!!\nToken Number : " + token);
                    return 1;
                } else {
                    JOptionPane.showMessageDialog(null, "Enter Valid Vehicle No");
                }/*from w w w.java2  s.c om*/
            } else {
                JOptionPane.showMessageDialog(null, "Enter Valid Passing Number");
            }
        } else {
            JOptionPane.showMessageDialog(null, "Enter Valid Mobile No");
        }
    } else {
        JOptionPane.showMessageDialog(null, "Enter Valid User Name");
    }
    return 0;
}

From source file:JavaSimpleExample.java

License:MIT License

public static void main(String[] args) throws UnknownHostException {

    // Create seed data

    final BasicDBObject[] seedData = createSeedData();

    // Standard URI format: mongodb://[dbuser:dbpassword@]host:port/dbname

    MongoClientURI uri = new MongoClientURI("mongodb://user:pass@host:port/db");
    MongoClient client = new MongoClient(uri);
    DB db = client.getDB(uri.getDatabase());

    /*//from w ww.ja  v  a2s  .c  om
     * First we'll add a few songs. Nothing is required to create the
     * songs collection; it is created automatically when we insert.
     */

    DBCollection songs = db.getCollection("songs");

    // Note that the insert method can take either an array or a document.

    songs.insert(seedData);

    /*
     * Then we need to give Boyz II Men credit for their contribution to
     * the hit "One Sweet Day".
     */

    BasicDBObject updateQuery = new BasicDBObject("song", "One Sweet Day");
    songs.update(updateQuery,
            new BasicDBObject("$set", new BasicDBObject("artist", "Mariah Carey ft. Boyz II Men")));

    /*
     * Finally we run a query which returns all the hits that spent 10 
     * or more weeks at number 1.
     */

    BasicDBObject findQuery = new BasicDBObject("weeksAtOne", new BasicDBObject("$gte", 10));
    BasicDBObject orderBy = new BasicDBObject("decade", 1);

    DBCursor docs = songs.find(findQuery).sort(orderBy);

    while (docs.hasNext()) {
        DBObject doc = docs.next();
        System.out.println("In the " + doc.get("decade") + ", " + doc.get("song") + " by " + doc.get("artist")
                + " topped the charts for " + doc.get("weeksAtOne") + " straight weeks.");
    }

    // Since this is an example, we'll clean up after ourselves.

    songs.drop();

    // Only close the connection when your app is terminating

    client.close();
}

From source file:DeleteRecord.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    MongoClient mongoClient;/*  ww w.  j av  a  2s .  com*/
    try {
        mongoClient = new MongoClient("localhost", 27017);
        DB db = mongoClient.getDB("Classic_Hangman");
        System.out.println("Connected to database successfully!!");
        BasicDBObject doc = new BasicDBObject();
        DBCollection coll = db.getCollection("movies");
        DBCollection coll1 = db.getCollection("counter");
        System.out.println("Collection selected successfully");
        DBObject c = coll1.findOne();
        int count = ((Number) c.get("count")).intValue();
        int del_id = Integer.parseInt(jTextField1.getText());
        doc.put("id", del_id);
        coll.remove(doc);
        for (int i = del_id + 1; i <= count; i++) {
            BasicDBObject newDocument = new BasicDBObject();
            newDocument.append("$set", new BasicDBObject().append("id", i - 1));
            BasicDBObject searchQuery = new BasicDBObject().append("id", i);
            coll.update(searchQuery, newDocument);
        }
        count--;
        coll1.remove(new BasicDBObject());
        BasicDBObject doc1 = new BasicDBObject("count", count);
        coll1.insert(doc1);
        JOptionPane.showMessageDialog(this, "Record deleted!");
    } catch (UnknownHostException ex) {
        Logger.getLogger(AdminLogin.class.getName()).log(Level.SEVERE, null, ex);
    }
}