@@ -400,11 +400,41 @@ void checkMaster( boolean force , boolean failIfNoMaster )
400400 }
401401 else {
402402 _set ( n ._addr );
403+ maxBsonObjectSize = _rsStatus .getMaxBsonObjectSize ();
403404 }
404405 }
406+ } else {
407+ // single server, may have to obtain max bson size
408+ if (maxBsonObjectSize == 0 )
409+ maxBsonObjectSize = fetchMaxBsonObjectSize ();
410+ }
411+ }
412+
413+ /**
414+ * Fetches the maximum size for a BSON object from the current master server
415+ * @return the size, or 0 if it could not be obtained
416+ */
417+ int fetchMaxBsonObjectSize () {
418+ if (_masterPortPool == null )
419+ return 0 ;
420+ DBPort port = _masterPortPool .get ();
421+ try {
422+ CommandResult res = port .runCommand (_mongo .getDB ("admin" ), new BasicDBObject ("isMaster" , 1 ));
423+ // max size was added in 1.8
424+ if (res .containsField ("maxBsonObjectSize" )) {
425+ maxBsonObjectSize = ((Integer ) res .get ("maxBsonObjectSize" )).intValue ();
426+ } else {
427+ maxBsonObjectSize = Bytes .MAX_OBJECT_SIZE ;
428+ }
429+ } catch (Exception e ) {
430+ _logger .log (Level .WARNING , null , e );
431+ } finally {
432+ port .getPool ().done (port );
405433 }
434+ return maxBsonObjectSize ;
406435 }
407436
437+
408438 void testMaster ()
409439 throws MongoException {
410440
@@ -469,13 +499,23 @@ public boolean isOpen(){
469499 return ! _closed ;
470500 }
471501
502+ /**
503+ * Gets the maximum size for a BSON object supported by the current master server.
504+ * Note that this value may change over time depending on which server is master.
505+ * @return the maximum size, or 0 if not obtained from servers yet.
506+ */
507+ public int getMaxBsonObjectSize () {
508+ return maxBsonObjectSize ;
509+ }
510+
472511 private Mongo _mongo ;
473512// private ServerAddress _curMaster;
474513 private DBPortPool _masterPortPool ;
475514 private DBPortPool .Holder _portHolder ;
476515 private final List <ServerAddress > _allHosts ;
477516 private final ReplicaSetStatus _rsStatus ;
478517 private boolean _closed = false ;
518+ private int maxBsonObjectSize = 0 ;
479519
480520 private ThreadLocal <MyPort > _myPort = new ThreadLocal <MyPort >(){
481521 protected MyPort initialValue (){
0 commit comments