Java Code Examples for com.mongodb.DB#command()

The following examples show how to use com.mongodb.DB#command() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MongoDBTestHelper.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
public static boolean isConfigServer(AbstractMongoDBServer entity) {
    LOG.info("Checking if {} is a config server", entity);
    MongoClient mongoClient = clientForServer(entity);
    try {
        DB db = mongoClient.getDB(ADMIN_DB);
        CommandResult commandResult = db.command("getCmdLineOpts");
        Map<?, ?> parsedArgs = (Map<?, ?>)commandResult.get("parsed");
        if (parsedArgs == null) return false;
        Boolean configServer = (Boolean)parsedArgs.get("configsvr");
        if (configServer != null) {
            // v2.5 format
            return Boolean.TRUE.equals(configServer);
        } else {
            // v2.6 format
            String role = (String) ((Map)parsedArgs.get("sharding")).get("clusterRole");
            return "configsvr".equals(role);
        }
    } finally {
        mongoClient.close();
    }
}
 
Example 2
Source File: MongoBenchmark.java    From gameserver with Apache License 2.0 6 votes vote down vote up
public static void testMongoUserId(int max, DB db) {
	String collName = "testmongobjid";
	DBCollection coll = db.getCollection(collName);
	
	//Setup a sharded collection
	BasicDBObject command = new BasicDBObject();
	command.put("shardcollection", collName);
	DBObject key = new BasicDBObject();
	key.put("_id", 1);
	command.put("key", key);
	command.put("unique", true);
	db.command(command);
	
	long startM = System.currentTimeMillis();
	for ( int i=0; i<max; i++ ) {
		BasicDBObject obj = new BasicDBObject();
		obj.put("test", "value-"+i);
		coll.save(obj);
	}
	long endM = System.currentTimeMillis();
	
	System.out.println("Insert " + max + " mongo objectid. time: " + (endM-startM) + " benchmark()");
	
	CommandResult result = db.getStats();
	System.out.println(result);
}
 
Example 3
Source File: MongoCommander.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
/**
 * get list of  the shards
 * @param dbConn
 * @return
 */
private static List<String> getShards(DB dbConn) {
    List<String> shards = new ArrayList<String>();

    DBObject listShardsCmd = new BasicDBObject("listShards", 1);
    CommandResult res = dbConn.command(listShardsCmd);
    if (!res.ok()) {
        LOG.error("Error getting shards for {}: {}", dbConn, res.getErrorMessage());
    }

    BasicDBList listShards = (BasicDBList) res.get("shards");

    //Only get shards for sharding mongo
    if (listShards != null) {
        ListIterator<Object> iter = listShards.listIterator();

        while (iter.hasNext()) {
            BasicDBObject shard = (BasicDBObject) iter.next();
            shards.add(shard.getString(ID));
        }
    }
    return shards;
}
 
Example 4
Source File: DBusMongoClient.java    From DBus with Apache License 2.0 5 votes vote down vote up
private boolean isReplSet() {
    boolean ret = false;
    DB db = new DB(mongoClient, "admin");
    CommandResult cr = db.command("replSetGetStatus");
    logger.info("isReplSet: {}", cr.toJson());
    if (cr.containsField("set") && cr.containsField("members")) {
        ret = true;
    }
    return ret;
}
 
Example 5
Source File: DBusMongoClient.java    From DBus with Apache License 2.0 5 votes vote down vote up
private boolean isShard() {
    boolean ret = false;
    DB db = new DB(mongoClient, "admin");
    CommandResult cr = db.command("isdbgrid");
    logger.info("isShard: {}", cr.toJson());
    if (cr.containsField("isdbgrid") && cr.getInt("isdbgrid") == 1) {
        ret = true;
    }
    return ret;
}
 
Example 6
Source File: MongoDBClientSupport.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
public boolean ping() {
    MongoClient client = fastClient();
    DBObject command = new BasicDBObject("ping", "1");
    final DB db = client.getDB("admin");

    try {
        CommandResult status = db.command(command);
        return status.ok();
    } catch (MongoException e) {
        LOG.warn("Pinging server {} failed with {}", address.getHost(), e);
    } finally {
        client.close();
    }
    return false;
}
 
Example 7
Source File: MongoDAL.java    From uncode-dal-all with GNU General Public License v2.0 5 votes vote down vote up
public void runScript(String script) {
    //有个格式化的作用
    try {
    	DB db = database.getDB();
        db.command(buildCommand(script));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 8
Source File: MongoBenchmark.java    From gameserver with Apache License 2.0 5 votes vote down vote up
public static void testMyUserId(int max, DB db) {
	String collName = "testmyuserid";
	DBCollection coll = db.getCollection(collName);
	
	//Setup a sharded collection
	BasicDBObject command = new BasicDBObject();
	command.put("shardcollection", collName);
	DBObject key = new BasicDBObject();
	key.put("_id", 1);
	command.put("key", key);
	command.put("unique", true);
	db.command(command);
	
	long startM = System.currentTimeMillis();
	BasicDBObject obj = new BasicDBObject();
	for ( int i=0; i<max; i++ ) {
		UserId userId = new UserId("username"+i);
		obj.put("_id",  userId.getInternal());
		obj.put("test", "value-"+i);
		coll.save(obj);
	}
	long endM = System.currentTimeMillis();
	
	System.out.println("Insert " + max + " my objectid. time: " + (endM-startM) + " benchmark()");
	
	CommandResult result = db.getStats();
	System.out.println(result);
}
 
Example 9
Source File: MongoBenchmark.java    From gameserver with Apache License 2.0 5 votes vote down vote up
public static void testStringUserId(int max, DB db) {
	String collName = "teststringid";
	DBCollection coll = db.getCollection(collName);
	
	//Setup a sharded collection
	BasicDBObject command = new BasicDBObject();
	command.put("shardcollection", collName);
	DBObject key = new BasicDBObject();
	key.put("_id", 1);
	command.put("key", key);
	command.put("unique", true);
	db.command(command);
	
	long startM = System.currentTimeMillis();
	BasicDBObject obj = new BasicDBObject();
	for ( int i=0; i<max; i++ ) {
		obj.put("_id",  "username"+i);
		obj.put("test", "value-"+i);
		coll.save(obj);
	}
	long endM = System.currentTimeMillis();
	
	System.out.println("Insert " + max + " my objectid. time: " + (endM-startM) + " benchmark()");
	
	CommandResult result = db.getStats();
	System.out.println(result);
}
 
Example 10
Source File: MongoBenchmark.java    From gameserver with Apache License 2.0 5 votes vote down vote up
public static void testBasicBson(int max, DB db) {
	String collName = "testbasicbson";
	DBCollection coll = db.getCollection(collName);
	
	//Setup a sharded collection
	BasicDBObject command = new BasicDBObject();
	command.put("shardcollection", collName);
	DBObject key = new BasicDBObject();
	key.put("_id", 1);
	command.put("key", key);
	command.put("unique", true);
	db.command(command);
	
	long startM = System.currentTimeMillis();
	BasicDBObject objKey = new BasicDBObject();
	UserId userId = new UserId("username");
	objKey.put("_id", userId.getInternal());
	
	BasicDBObject obj = new BasicDBObject();
	for ( int i=0; i<max; i++ ) {
		obj.put("_id", userId.getInternal());
		obj.put("test-"+(i)%10, "value-"+i);
		coll.update(objKey, obj, true, false);
	}
	long endM = System.currentTimeMillis();
	
	System.out.println(collName+ " update " + max + " my objectid. time: " + (endM-startM) + " benchmark(56273)");
	
	CommandResult result = db.getStats();
	System.out.println(result);
}
 
Example 11
Source File: MongoBenchmark.java    From gameserver with Apache License 2.0 5 votes vote down vote up
public static void testMapDBObject(int max, DB db) {
	String collName = "testmapobject";
	DBCollection coll = db.getCollection(collName);
	
	//Setup a sharded collection
	BasicDBObject command = new BasicDBObject();
	command.put("shardcollection", collName);
	DBObject key = new BasicDBObject();
	key.put("_id", 1);
	command.put("key", key);
	command.put("unique", true);
	db.command(command);
	
	long startM = System.currentTimeMillis();
	BasicDBObject objKey = new BasicDBObject();
	UserId userId = new UserId("username");
	objKey.put("_id", userId.getInternal());
	
	MapDBObject obj = new MapDBObject();
	for ( int i=0; i<max; i++ ) {
		obj.put("_id", userId.getInternal());
		obj.put("test-"+(i)%10, "value-"+i);
		coll.update(objKey, obj, true, false);
	}
	long endM = System.currentTimeMillis();
	
	System.out.println(collName+ " update " + max + " my objectid. time: " + (endM-startM) + " benchmark(114892)");
	
	CommandResult result = db.getStats();
	System.out.println(result);
}
 
Example 12
Source File: MongoCommander.java    From secure-data-service with Apache License 2.0 4 votes vote down vote up
/**
 * Pre-split database
 * @param shardCollections: the set of collections to be split
 * @param dbName
 * @param mongoTemplate
 * @return Error description, or null if no errors
 */
public static String preSplit(Set<String> shardCollections, String dbName, MongoTemplate mongoTemplate) {
    DB dbConn = mongoTemplate.getDb().getSisterDB("admin");

    //Don't do anything if it is non-sharded
    List<String> shards = getShards(dbConn);
    if (shards.size() == 0) {
        return null;
    }

    //set balancer off
    String sresult = setBalancerState(dbConn, false);
    if (sresult != null) {
        return sresult;
    }

    // Enable sharding for this database
    DBObject enableShard = new BasicDBObject("enableSharding", dbName);
    CommandResult result = dbConn.command(enableShard);
    if (!result.ok()) {
        LOG.error("Error enabling sharding on {}: {}", dbConn, result.getErrorMessage());
        return result.getErrorMessage();
    }

    for (String coll : shardCollections) {
        String collection = dbName + "." + coll;

        // Enable sharding for this collection, sharding on _id
        DBObject shardColl = new BasicDBObject();
        shardColl.put("shardCollection", collection);
        shardColl.put("key", new BasicDBObject(ID, 1));
        result = dbConn.command(shardColl);
        if (!result.ok()) {
            LOG.error("Error enabling shard'ing on {}: {}", collection, result.getErrorMessage());
           return result.getErrorMessage();
        }

        sresult = moveChunks(collection, shards, dbConn);
        if (sresult != null) {
            return sresult;
        }
    }
    return preSplitBinCollections(dbName, mongoTemplate);
}
 
Example 13
Source File: MongoCommander.java    From secure-data-service with Apache License 2.0 4 votes vote down vote up
private static String preSplitBinCollections(String dbName,  MongoTemplate mongoTemplate) {
    DB dbConn = mongoTemplate.getDb().getSisterDB("admin");
    List<String> shards = getShards(dbConn);
    if (shards != null && shards.size() > 0) {
        int numShards = shards.size();
        List<String> collections = Arrays.asList("recordHash", "deltas");
        for (String collectionName: collections) {
            LOG.info("Shard count = {}. Setting up sharding config for {}!", numShards, collectionName);
            String collection = dbName + "." + collectionName;
            DBObject shardColl = new BasicDBObject();
            shardColl.put("shardCollection", collection);
            shardColl.put("key", new BasicDBObject(ID, 1));
            CommandResult result = dbConn.command(shardColl);
            if (!result.ok()) {
                LOG.error("Error enabling shard'ing on recordHash: {}", result.getErrorMessage());
                return result.getErrorMessage();
            }
            int charOffset = 256 / numShards;
            List<byte[]> shardPoints = new ArrayList<byte[]>();
            shardPoints.add(null);
            for (int shard = 1; shard < numShards; shard++) {
                String splitString = Integer.toHexString(charOffset * shard);
                if (splitString.length() < 2) {
                    splitString = "0" + splitString;
                }

                splitString = splitString + STR_0X38;
                byte[] splitPoint = RecordHash.hex2Binary(splitString);
                shardPoints.add(splitPoint);
                LOG.info("Adding recordHash splitPoint [" + RecordHash.binary2Hex(splitPoint) + "]");

                DBObject splitCmd = new BasicDBObject();
                splitCmd.put("split", collection);
                splitCmd.put("middle", new BasicDBObject(ID, splitPoint));
                result = dbConn.command(splitCmd);
                if (!result.ok()) {
                    LOG.error("Error splitting chunk in recordHash: {}", result.getErrorMessage());
                    return result.getErrorMessage();
                }
            }
            for (int index = 0; index < numShards; index++) {
                DBObject moveCommand = new BasicDBObject();
                moveCommand.put("moveChunk", collection);
                moveCommand.put("find", new BasicDBObject(ID, index == 0 ? "$minkey" : shardPoints.get(index)));
                moveCommand.put("to", shards.get(index));
                result = dbConn.command(moveCommand);
                if (!result.ok()) {
                    if (!result.getErrorMessage().equals("that chunk is already on that shard")) {
                        LOG.error("Error moving chunk in recordHash: {}", result.getErrorMessage());
                        return result.getErrorMessage();
                    }
                }
            }
        }
    } else {
        LOG.info("No shards or shard count < 0. Not setting sharding config for recordHash!");
    }
    return null;
}