Example usage for com.mongodb DBCollection findOne

List of usage examples for com.mongodb DBCollection findOne

Introduction

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

Prototype

@Nullable
public DBObject findOne() 

Source Link

Document

Get a single document from collection.

Usage

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;/*from w w w .  j  a  v  a  2  s.c o  m*/
    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);
    }
}

From source file:AddRecord.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    int flag = 0;
    try {/*from  w w  w.j  a v  a2  s.c o m*/
        // TODO add your handling code here:
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        db = mongoClient.getDB("Classic_Hangman");
        System.out.println("Connected to database successfully!!");
        BasicDBObject d = new BasicDBObject();
        String movie = jTextField1.getText();
        //String genre = jTextField2.getText();
        String director = jTextField3.getText();
        for (int i = 0; i < director.length(); i++) {
            if (Character.isDigit(director.charAt(i))) {
                JOptionPane.showMessageDialog(this, "Invalid director entry!");
                flag = 1;
                break;
            }
        }
        if (movie.equals("") || genre.equals("")) {
            JOptionPane.showMessageDialog(this, "Empty Field!");
        } else {
            if (flag != 1) {
                DBCollection coll = db.getCollection("movies");
                DBCollection coll1 = db.getCollection("counter");
                System.out.println("Collection selected successfully");
                BasicDBObject query = new BasicDBObject();
                DBObject c = coll1.findOne();
                count = ((Number) c.get("count")).intValue();
                System.out.println("Count = " + count);
                //count = (int)c.get("count");
                BasicDBObject doc = new BasicDBObject("id", count + 1).append("name", movie)
                        .append("director", director).append("genre", genre);
                coll.insert(doc);
                System.out.println("Document inserted successfully");
                count++;
                /*DBCursor cursor = coll.find();
                int i=1;
                while (cursor.hasNext()) { 
                    System.out.println("Inserted Document: "+i); 
                    System.out.println(cursor.next()); 
                    i++;
                }*/
                //DBCollection coll1 = db.getCollection("counter");
                //System.out.println("Collection selected successfully");
                coll1.remove(new BasicDBObject());
                BasicDBObject doc1 = new BasicDBObject("count", count);
                coll1.insert(doc1);
                /*cursor = coll.find();
                BasicDBObject newDocument = new BasicDBObject();
                System.out.println(count);
                newDocument.put("count", count);
                BasicDBObject searchQuery = new BasicDBObject().append("count", count);
                coll.update(searchQuery, newDocument);*/
                jTextField1.setText("");
                //jTextField2.setText("");
                jTextField3.setText("");
                JOptionPane.showMessageDialog(this, "Record added!");
            }
        }
    } catch (UnknownHostException ex) {
        //Logger.getLogger(AdminLogin.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:br.bireme.scl.BrokenLinks.java

License:Open Source License

public static int createLinks(final String outCheckFile, final String outEncoding, final String mstName,
        final String mstEncoding, final String host, final int port, final String user, final String password,
        final boolean clearCol, final String[] allowedMessages) throws BrumaException, IOException {
    if (outCheckFile == null) {
        throw new NullPointerException("outCheckFile");
    }/*from w w  w.  j a  va 2  s .  c o m*/
    if (outEncoding == null) {
        throw new NullPointerException("outEncoding");
    }
    if (mstName == null) {
        throw new NullPointerException("mstName");
    }
    if (mstEncoding == null) {
        throw new NullPointerException("mstEncoding");
    }
    if (host == null) {
        throw new NullPointerException("host");
    }
    if (port <= 0) {
        throw new IllegalArgumentException("port <= 0");
    }
    if (allowedMessages == null) {
        throw new NullPointerException("allowedMessages");
    }

    final Master mst = MasterFactory.getInstance(mstName).setEncoding(mstEncoding).open();
    final String mName = new File(mst.getMasterName()).getName();
    final BufferedReader in = new BufferedReader(
            new InputStreamReader(new FileInputStream(outCheckFile), outEncoding));
    final MongoClient mongoClient = new MongoClient(host, port);
    final DB db = mongoClient.getDB(SOCIAL_CHECK_DB);
    // map -> mfn ->  url,occ
    final Map<Integer, Map<String, Integer>> occMap = new HashMap<Integer, Map<String, Integer>>();
    final boolean checkPassword = false;
    if (checkPassword) {
        final boolean auth = db.authenticate(user, password.toCharArray());
        if (!auth) {
            throw new IllegalArgumentException("invalid user/password");
        }
    }

    final DBCollection coll = db.getCollection(BROKEN_LINKS_COL);
    final DBCollection ccColl = db.getCollection(CC_FIELDS_COL);
    final DBCollection hColl = db.getCollection(HISTORY_COL);

    if (ccColl.findOne() == null) {
        if (!createCcFieldsCollection(ccColl)) {
            throw new IOException("CC fields collection creation failed");
        }
    }
    final int idTag = getIsisIdField(mName, ccColl);
    final int urlTag = getIsisUrlFields(mName, ccColl);
    if (urlTag <= 0) {
        throw new IOException("Missing Isis url fields");
    }
    final List<Integer> tags = getIsisCcFields(mName, ccColl);
    final Set<String> allowedMess = new HashSet<String>(Arrays.asList(allowedMessages));
    final Map<String, Integer> idMap = getIdMfn(mst, idTag);
    int tell = 0;
    int tot = 0;

    if (clearCol) {
        coll.dropIndexes();
        coll.remove(new BasicDBObject());
    }

    System.out.println("Saving documents ...");
    while (true) {
        final String line = in.readLine();
        if (line == null) {
            break;
        }
        final String lineT = line.trim();
        if (!lineT.isEmpty()) {
            final String[] split = lineT.split(" *\\| *", 4); //id|url|msg|master
            if (split.length < 4) {
                throw new IOException("Wrong line format: " + line);
            }
            final int openPos = split[2].indexOf('('); // cut extra data               
            final String prefix = (openPos > 0) ? split[2].substring(0, openPos) : split[2];

            if (allowedMess.contains(prefix.trim())) {
                final Integer id = idMap.get(split[0]);
                if (id == null) {
                    throw new IOException("id[" + split[0] + "] not found");
                }

                final String url_e = EncDecUrl.encodeUrl(split[1], outEncoding, false);

                saveRecord(mName, id, url_e, split[2], urlTag, tags, mst, coll, hColl, occMap);
                tot++;
            }
            if (++tell % 5000 == 0) {
                System.out.println("++" + tell);
            }
        }
    }

    System.out.print("\nFixing urls that do not start with http:// ... ");
    MongoOperations.fixMissingHttp(coll, hColl);
    System.out.println(" - OK");

    //removeOldDocs(coll);

    if (clearCol) {
        createIndex(coll);
    }

    in.close();
    mst.close();

    return tot;
}

From source file:com.arquivolivre.mongocom.utils.IntegerGenerator.java

License:Apache License

@Override
public Integer generateValue(Class parent, DB db) {
    DBCollection collection = db.getCollection("values_" + parent.getSimpleName());
    DBObject o = collection.findOne();
    int value = 0;
    if (o != null) {
        value = (int) o.get("generatedValue");
    } else {//w  w  w.ja  v a  2 s.  c  o  m
        o = new BasicDBObject("generatedValue", value);
    }
    o.put("generatedValue", ++value);
    collection.save(o);
    return value;
}

From source file:com.edgytech.umongo.ReplSetNode.java

License:Apache License

@Override
protected void populateChildren() {
    // need to make a query to update server list
    try {// www.  jav  a  2s.  c  o  m
        mongo.getDatabaseNames();
    } catch (Exception e) {
        getLogger().log(Level.WARNING, null, e);
    }

    // need to pull servers from configuration to see hidden
    //        List<ServerAddress> addrs = mongo.getServerAddressList();
    final DBCollection col = mongo.getDB("local").getCollection("system.replset");
    DBObject config = col.findOne();
    if (config == null) {
        getLogger().log(Level.WARNING, "No replica set configuration found");
        return;
    }

    BasicDBList members = (BasicDBList) config.get("members");
    for (int i = 0; i < members.size(); ++i) {
        String host = (String) ((DBObject) members.get(i)).get("host");
        try {
            // this will create new MongoClient instance, catch any exception
            addChild(new ServerNode(host, mongo.getMongoClientOptions(), true, false));
        } catch (Exception e) {
            getLogger().log(Level.WARNING, null, e);
        }
    }
}

From source file:com.edgytech.umongo.ReplSetPanel.java

License:Apache License

public void reconfigure(ButtonBase button) {
    final DBCollection col = getReplSetNode().getMongoClient().getDB("local").getCollection("system.replset");
    DBObject oldConf = col.findOne();
    if (oldConf == null) {
        new InfoDialog(null, "reconfig error", null, "No existing replica set configuration").show();
        return;//from   ww  w  .  j  av  a 2s  .c o m
    }
    ((DocBuilderField) getBoundUnit(Item.reconfConfig)).setDBObject(oldConf);
    if (!((MenuItem) getBoundUnit(Item.reconfigure)).getDialog().show())
        return;

    DBObject config = ((DocBuilderField) getBoundUnit(Item.reconfConfig)).getDBObject();
    reconfigure(getReplSetNode(), config);
}

From source file:com.edgytech.umongo.ReplSetPanel.java

License:Apache License

static public void reconfigure(final ReplSetNode rsNode, DBObject config) {
    final DBCollection col = rsNode.getMongoClient().getDB("local").getCollection("system.replset");
    DBObject oldConf = col.findOne();
    int version = ((Integer) oldConf.get("version")) + 1;
    config.put("version", version);

    // reconfig usually triggers an error as connections are bounced.. try to absorb it
    final DBObject cmd = new BasicDBObject("replSetReconfig", config);
    final DB admin = rsNode.getMongoClient().getDB("admin");

    new DbJob() {

        @Override/*from  w  w w  . j ava 2s.  c om*/
        public Object doRun() {
            Object res = null;
            try {
                res = admin.command(cmd);
            } catch (MongoException.Network e) {
                res = new BasicDBObject("msg", "Operation was likely successful, but connection was bounced");
            }

            try {
                // sleep a bit since it takes time for driver to see change
                Thread.sleep(6000);
            } catch (InterruptedException ex) {
                getLogger().log(Level.WARNING, null, ex);
            }
            return res;
        }

        @Override
        public String getNS() {
            return null;
        }

        @Override
        public String getShortName() {
            return "RS Reconfig";
        }

        @Override
        public DBObject getRoot(Object result) {
            return cmd;
        }

        @Override
        public void wrapUp(Object res) {
            // try to restructure but changes arent seen for a few seconds
            super.wrapUp(res);
            rsNode.structureComponent();
        }
    }.addJob();
}

From source file:com.edgytech.umongo.ReplSetPanel.java

License:Apache License

public void addReplica(ButtonBase button) {
    final DBCollection col = getReplSetNode().getMongoClient().getDB("local").getCollection("system.replset");
    DBObject config = col.findOne();
    if (config == null) {
        new InfoDialog(null, "reconfig error", null, "No existing replica set configuration").show();
        return;// ww w  .ja v a  2s .c  om
    }

    BasicDBList members = (BasicDBList) config.get("members");
    int max = 0;
    for (int i = 0; i < members.size(); ++i) {
        int id = (Integer) ((DBObject) members.get(i)).get("_id");
        if (id > max)
            max = id;
    }

    ReplicaDialog dia = UMongo.instance.getGlobalStore().getReplicaDialog();
    if (!dia.show())
        return;
    BasicDBObject conf = dia.getReplicaConfig(max + 1);
    members.add(conf);
    reconfigure(getReplSetNode(), config);
}

From source file:com.edgytech.umongo.ServerPanel.java

License:Apache License

public void rsRemove(ButtonBase button) throws Exception {
    ReplSetNode replset = (ReplSetNode) getServerNode().getParentNode();
    final DBCollection col = replset.getMongoClient().getDB("local").getCollection("system.replset");
    DBObject config = col.findOne();

    BasicDBList members = (BasicDBList) config.get("members");
    int i = 0;/*w  w  w .  j a  v  a2s .c o m*/
    String myhost = getServerNode().getServerAddress().getHost() + ":"
            + getServerNode().getServerAddress().getPort();
    for (; i < members.size(); ++i) {
        if (myhost.equals(((DBObject) members.get(i)).get("host")))
            break;
    }

    if (i == members.size()) {
        throw new Exception("No such server in configuration");
    }

    members.remove(i);
    ReplSetPanel.reconfigure(replset, config);
}

From source file:com.edgytech.umongo.ServerPanel.java

License:Apache License

public void rsReconfigure(ButtonBase button) throws Exception {
    ReplSetNode replset = (ReplSetNode) getServerNode().getParentNode();
    final DBCollection col = replset.getMongoClient().getDB("local").getCollection("system.replset");
    DBObject config = col.findOne();

    BasicDBList members = (BasicDBList) config.get("members");
    int i = 0;// w  w w. j ava  2s. c o m
    String myhost = getServerNode().getServerAddress().getHost() + ":"
            + getServerNode().getServerAddress().getPort();
    for (; i < members.size(); ++i) {
        if (myhost.equals(((DBObject) members.get(i)).get("host")))
            break;
    }

    if (i == members.size()) {
        throw new Exception("No such server in configuration");
    }

    ReplicaDialog dia = UMongo.instance.getGlobalStore().getReplicaDialog();
    BasicDBObject oldConf = (BasicDBObject) members.get(i);
    dia.updateFromReplicaConfig(oldConf);
    if (!dia.show())
        return;
    BasicDBObject conf = dia.getReplicaConfig(oldConf.getInt("_id"));
    members.put(i, conf);

    ReplSetPanel.reconfigure(replset, config);
}