【问题标题】:Programmatically set shard key with MongoDB Java Driver使用 MongoDB Java 驱动程序以编程方式设置分片键
【发布时间】:2014-06-17 16:03:32
【问题描述】:

从 MongoDB Java 驱动程序版本 2.10.1 设置分片键的语法是什么?

或者换句话说,我如何使用 Java 驱动程序做到这一点?

sh.shardCollection("test.a", {"_id": "hashed"}})

【问题讨论】:

    标签: mongodb mongodb-java


    【解决方案1】:

    简短回答:您应该发出shardCollection 命令。

    长答案:

    MongoDB shell 中的sh.shardCollection 只是在admin db 上调用命令的辅助方法。

    如果你在 MongoDB shell 中输入sh.shardCollection,你会看到这个函数实际上在做什么:

    > sh.shardCollection
    function ( fullName , key , unique ) {
        sh._checkFullName( fullName )
        assert( key , "need a key" )
        assert( typeof( key ) == "object" , "key needs to be an object" )
    
        var cmd = { shardCollection : fullName , key : key }
        if ( unique )
            cmd.unique = true;
    
        return sh._adminCommand( cmd );
    }
    

    然后您可以在 MongoDB shell 中调用 sh._adminCommand

    > sh._adminCommand
    function ( cmd , skipCheck ) {
        if ( ! skipCheck ) sh._checkMongos();
        return db.getSisterDB( "admin" ).runCommand( cmd );
    }
    

    当你把所有东西放在一起时,sh.shardCollection 命令所做的就是检查参数并调用这个命令:

    db.getSisterDB( "admin" ).runCommand({ 
        shardCollection : "test.a" , 
        key : {"_id": "hashed"}
    });
    

    Java 语法:

    DBObject cmd = new BasicDBObject("shardCollection", "test.a").
      append("key",new BasicDBObject("_id", "hashed"));
    CommandResult r = db.getSisterDB("admin").command(cmd);
    

    【讨论】:

      【解决方案2】:

      通过 Java api 设置分片:

      CommandResult result=null; 
      
      // The only way to shard this is via executing a command. If this is not
      // done the collection will becreated but it will not be 
      // sharded. The first arg is the key and the second one is the logic to be used
      final BasicDBObject shardKey = new BasicDBObject("_id", "hashed"); 
      
      final BasicDBObject cmd = new BasicDBObject("shardCollection", "test."+collectionName); 
      cmd.put("key", shardKey); 
      
      // RUnning the command to create the sharded collection
      result = mongoClient.getDB("admin").command(cmd); 
      System.out.println("Collection created successfully");
      
      // loading the collection and then will be insterting the data
      final DBCollection shardCollection = mongoClient.getDB("test").getCollection(collectionName); 
      
      // Here i am using a arraylist values which has all the data
      shardCollection.insert(values);
      System.out.println("Collection added");
      

      【讨论】:

        【解决方案3】:

        没有用于此的 API。您必须发出命令来设置该分片键。

        【讨论】:

          猜你喜欢
          • 2020-06-14
          • 2019-03-23
          • 1970-01-01
          • 1970-01-01
          • 2016-03-13
          • 2013-11-09
          • 2017-03-10
          • 2012-11-26
          • 2017-03-10
          相关资源
          最近更新 更多