Example usage for com.mongodb DBCollection getDB

List of usage examples for com.mongodb DBCollection getDB

Introduction

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

Prototype

public DB getDB() 

Source Link

Document

Returns the database this collection is a member of.

Usage

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

License:Apache License

public void dropCollection(ButtonBase button) {
    final CollectionNode colNode = getCollectionNode();
    final DBCollection col = getCollectionNode().getCollection();
    BasicDBObject cmd = new BasicDBObject("drop", col.getName());
    new DbJobCmd(col.getDB(), cmd, null, colNode.getDbNode(), null).addJob();
}

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

License:Apache License

public void count(final ButtonBase button) {
    final DBCollection col = getCollectionNode().getCollection();
    final DBObject query = ((DocBuilderField) getBoundUnit(Item.countQuery)).getDBObject();
    final int skip = getIntFieldValue(Item.countSkip);
    final int limit = getIntFieldValue(Item.countLimit);

    BasicDBObject cmd = new BasicDBObject();
    cmd.put("count", col.getName());
    cmd.put("query", query);

    if (limit > 0) {
        cmd.put("limit", limit);
    }//ww w .  j av  a2 s .c om
    if (skip > 0) {
        cmd.put("skip", skip);
    }
    new DbJobCmd(col.getDB(), cmd, null, button).addJob();
}

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

License:Apache License

public void findAndModify(final ButtonBase button) {
    final DBCollection col = getCollectionNode().getCollection();
    final DBObject query = ((DocBuilderField) getBoundUnit(Item.famQuery)).getDBObject();
    final DBObject fields = ((DocBuilderField) getBoundUnit(Item.famFields)).getDBObject();
    final DBObject sort = ((DocBuilderField) getBoundUnit(Item.famSort)).getDBObject();
    final BasicDBObject update = (BasicDBObject) ((DocBuilderField) getBoundUnit(Item.famUpdate)).getDBObject();
    final boolean remove = getBooleanFieldValue(Item.famRemove);
    final boolean returnNew = getBooleanFieldValue(Item.famReturnNew);
    final boolean upsert = getBooleanFieldValue(Item.famUpsert);

    BasicDBObject cmd = new BasicDBObject("findandmodify", col.getName());
    if (query != null && !query.keySet().isEmpty()) {
        cmd.append("query", query);
    }/*from ww w  .j  a  v a  2 s.  c o  m*/
    if (fields != null && !fields.keySet().isEmpty()) {
        cmd.append("fields", fields);
    }
    if (sort != null && !sort.keySet().isEmpty()) {
        cmd.append("sort", sort);
    }

    if (remove) {
        cmd.append("remove", remove);
    } else {
        if (update != null && !update.keySet().isEmpty()) {
            // if 1st key doesn't start with $, then object will be inserted as is, need to check it
            String key = update.keySet().iterator().next();
            if (key.charAt(0) != '$') {
                MongoUtils.checkObject(update, false, false);
            }
            cmd.append("update", (DBObject) update.copy());
        }
        if (returnNew) {
            cmd.append("new", returnNew);
        }
        if (upsert) {
            cmd.append("upsert", upsert);
        }
    }

    new DbJobCmd(col.getDB(), cmd, null, button).addJob();
}

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

License:Apache License

public void fixCollection(ButtonBase button) {
    final MongoClient m = getCollectionNode().getDbNode().getMongoNode().getMongoClient();
    ArrayList<MongoNode> mongoNodes = UMongo.instance.getMongos();
    String[] mongonames = new String[mongoNodes.size() - 1];
    MongoClient[] mongos = new MongoClient[mongonames.length];
    int i = 0;//www .j av  a  2s  .c  o m
    for (MongoNode node : mongoNodes) {
        MongoClient m2 = node.getMongoClient();
        if (m == m2) {
            continue;
        }
        mongonames[i] = m2.toString();
        mongos[i] = m2;
        ++i;
    }
    ComboBox src = (ComboBox) getBoundUnit(Item.fcSrcMongo);
    src.items = mongonames;
    src.structureComponent();
    FormDialog dialog = (FormDialog) getBoundUnit(Item.fcDialog);
    if (!dialog.show()) {
        return;
    }

    final DBCollection dstCol = getCollectionNode().getCollection();
    final MongoClient srcMongo = mongos[src.getIntValue()];
    final boolean upsert = getBooleanFieldValue(Item.fcUpsert);

    final String dbname = dstCol.getDB().getName();
    final String colname = dstCol.getName();
    final DBCollection srcCol = srcMongo.getDB(dbname).getCollection(colname);
    String txt = "About to copy from ";
    txt += srcMongo.getConnectPoint() + "(" + srcCol.count() + ")";
    txt += " to ";
    txt += m.getConnectPoint() + "(" + dstCol.count() + ")";
    if (!new ConfirmDialog(null, "Confirm Fix Collection", null, txt).show()) {
        return;
    }

    new DbJob() {
        @Override
        public Object doRun() {
            DBCursor cur = srcCol.find();
            int count = 0;
            int dup = 0;
            while (cur.hasNext()) {
                DBObject obj = cur.next();
                if (upsert) {
                    BasicDBObject id = new BasicDBObject("_id", obj.get("_id"));
                    dstCol.update(id, obj, true, false);
                } else {
                    try {
                        dstCol.insert(obj);
                    } catch (DuplicateKey e) {
                        // dup keys are expected here
                        ++dup;
                    }
                }
                ++count;
            }
            DBObject res = new BasicDBObject("count", count);
            res.put("dups", dup);
            return res;
        }

        @Override
        public String getNS() {
            return "*";
        }

        @Override
        public String getShortName() {
            return "Fix Collection";
        }
    }.addJob();
}

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

License:Apache License

public DbJobCmd(DBCollection col, String cmdStr) {
    this(col.getDB(), new BasicDBObject(cmdStr, col.getName()), null, null);
}

From source file:com.hangum.tadpole.mongodb.core.editors.mapreduce.MapReduceEditor.java

License:Open Source License

private void goMapReduce(final DBCollection dbCol, final BasicDBObject basicObj,
        final MapReduceCommand.OutputType mrOType) {
    Job job = new Job("MapReduce search job") { //$NON-NLS-1$
        @Override/*from  www.j a  v a  2 s .  c  o m*/
        public IStatus run(IProgressMonitor monitor) {
            monitor.beginTask("Starting JSON query...", IProgressMonitor.UNKNOWN); //$NON-NLS-1$
            try {

                //               if(mrOType == MapReduceCommand.OutputType.INLINE) {
                //                  cmdResult = dbCol.getDB().command(basicObj, dbCol.getOptions());
                //                  cmdResult.throwOnError();
                //                  mrOutput = new MapReduceOutput(dbCol, basicObj, cmdResult);
                //               } else {
                cmdResult = dbCol.getDB().command(basicObj);
                //                  cmdResult.throwOnError();
                //                  mrOutput = new MapReduceOutput(dbCol, basicObj, cmdResult);
                //               }
                if (!cmdResult.ok()) {
                    throw cmdResult.getException();
                }

            } catch (Exception e) {
                logger.error("mapreduce exception", e); //$NON-NLS-1$
                return new Status(Status.WARNING, Activator.PLUGIN_ID, "mapreduce " + e.getMessage()); //$NON-NLS-1$
            } finally {
                monitor.done();
            }

            return Status.OK_STATUS;
        }
    };

    // job? event  ?.
    job.addJobChangeListener(new JobChangeAdapter() {
        public void done(IJobChangeEvent event) {

            final IJobChangeEvent jobEvent = event;
            getSite().getShell().getDisplay().asyncExec(new Runnable() {
                public void run() {
                    if (jobEvent.getResult().isOK()) {
                        try {
                            Iterable<DBObject> iteResult = (Iterable<DBObject>) cmdResult.get("results");
                            compositeResult.refreshDBView(iteResult, 0);
                            compositeResult.setResult();
                        } catch (Exception e) {
                            logger.error("MapReduce Error", e); //$NON-NLS-1$
                            Status errStatus = new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(),
                                    e); //$NON-NLS-1$
                            ExceptionDetailsErrorDialog.openError(null, "Error", "MapReduce execute exception", //$NON-NLS-1$//$NON-NLS-2$
                                    errStatus);
                        }
                    } else {
                        //                     compositeResult.errorView(jobEvent.getResult().getMessage());
                    }
                }
            }); // end display.asyncExec            
        } // end done
    }); // end job

    job.setName(userDB.getDisplay_name());
    job.setUser(true);
    job.schedule();
}

From source file:com.ibm.gaiandb.mongodb.MongoConnectionFactory.java

License:Open Source License

/**
 * Closes the Mongo Collection object - frees up any resources held by the collection and the related
 * connection object.//from  w  w  w .j  a  v a  2s.c  o  m
 * 
 * @param connectionParams - object containing all the parameters needed to connect to MongoDB
 * @exception UnknownHostException - if we cannot connect to the mongoDB host specified
 * @exception AuthenticationException - if authentication with the mongoDB process fails.
 * 
 */
public static void closeMongoCollection(DBCollection mongoCollection) {
    //we have to close the mongo client object, get a reference to it via the database object.
    DB mongoDB = mongoCollection.getDB();
    MongoClient mongoClient = (MongoClient) mongoDB.getMongo();
    mongoClient.close();

}

From source file:com.nesscomputing.mongo.MongoWriter.java

License:Apache License

synchronized void stop() {
    final Thread thread = writerThread.getAndSet(null);
    if (thread != null) {
        LOG.info("Stopping Mongo Writer for collection %s.", collectionName);
        try {//from   www .  ja va 2  s  .co  m
            taskRunning.set(false);
            thread.interrupt();
            thread.join(500L);
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
        }

        final DBCollection collection = dbCollection.getAndSet(null);
        if (collection != null) {
            final Mongo mongo = collection.getDB().getMongo();
            mongo.close();
        }
    } else {
        LOG.debug("Never started, ignoring stop()");
    }
}

From source file:com.qbao.cat.plugin.db.nosql.OldMongoPluginTemplate.java

License:Apache License

protected Transaction beginLog(ProceedingJoinPoint pjp) {
    Transaction transaction = null;//from w w  w . j av a 2  s  .c  o  m
    transaction = newTransaction("MongoDB", String.valueOf(pjp.getSignature().toShortString()));
    DBCollection collector = (DBCollection) pjp.getTarget();
    Cat.logEvent("Host", collector.getDB().getMongo().getServerAddressList().toString());
    Cat.logEvent("Connection", collector.toString());
    Cat.logEvent("DB", collector.getDB().getName());
    Cat.logEvent("Method", pjp.getSignature().toString());
    return transaction;
}

From source file:com.stratio.connector.mongodb.core.engine.metadata.DiscoverMetadataUtils.java

License:Apache License

/**
 * Discover the existing fields stored in the collection.
 *
 * @param collection//ww  w  . j  a  v a 2 s  . c  om
 * the collection
 * @return the list of fields including the _id
 */
public static List<String> discoverField(DBCollection collection) {
    String map = "function() { for (var field in this) { emit(field, null); }}";
    String reduce = "function(field, stuff) { return null; }";
    MapReduceCommand mapReduceCommand = new MapReduceCommand(collection, map, reduce, null, OutputType.INLINE,
            null);
    DBObject getFieldsCommand = mapReduceCommand.toDBObject();
    CommandResult command = collection.getDB().command(getFieldsCommand);
    BasicDBList results = (BasicDBList) command.get("results");
    Set<String> fields = new HashSet<>();
    if (results != null) {
        for (Object object : results) {
            DBObject bson = (DBObject) object;
            fields.add((String) bson.get("_id"));
        }
    }
    return new ArrayList<String>(fields);
}