com.mongodb
Class DB

java.lang.Object
  extended by com.mongodb.DB
Direct Known Subclasses:
DBApiLayer

public abstract class DB
extends Object

an abstract class that represents a logical database on a server


MongoDB Doc Links

Field Summary
protected  boolean _readOnly
           
 
Constructor Summary
DB(Mongo mongo, String name)
           
 
Method Summary
 void addOption(int option)
          Adds the give option
 WriteResult addUser(String username, char[] passwd)
          Adds a new user for this db
 WriteResult addUser(String username, char[] passwd, boolean readOnly)
          Adds a new user for this db
 boolean authenticate(String username, char[] password)
          Authenticates to db with the given credentials.
 CommandResult authenticateCommand(String username, char[] password)
          Authenticates to db with the given credentials.
abstract  void cleanCursors(boolean force)
           
 boolean collectionExists(String collectionName)
          Checks to see if a collection by name %lt;name> exists.
 CommandResult command(DBObject cmd)
          Executes a database command.
 CommandResult command(DBObject cmd, DBEncoder encoder)
          Executes a database command.
 CommandResult command(DBObject cmd, int options)
          Executes a database command.
 CommandResult command(DBObject cmd, int options, DBEncoder encoder)
          Executes a database command.
 CommandResult command(DBObject cmd, int options, ReadPreference readPrefs)
          Executes a database command.
 CommandResult command(DBObject cmd, int options, ReadPreference readPrefs, DBEncoder encoder)
          Executes a database command.
 CommandResult command(String cmd)
          Executes a database command.
 CommandResult command(String cmd, int options)
          Executes a database command.
 DBCollection createCollection(String name, DBObject options)
          Creates a collection with a given name and options.
 CommandResult doEval(String code, Object... args)
          evaluates a function on the database.
protected abstract  DBCollection doGetCollection(String name)
          Returns the collection represented by the string <dbName>.<collectionName>.
 void dropDatabase()
          Drops this database.
 Object eval(String code, Object... args)
          calls doEval(java.lang.String, java.lang.Object[]).
 void forceError()
          For testing purposes only - this method forces an error to help test error handling
 DBCollection getCollection(String name)
          Gets a collection with a given name.
 DBCollection getCollectionFromString(String s)
          Returns a collection matching a given string.
 Set<String> getCollectionNames()
          Returns a set containing the names of all collections in this database.
 CommandResult getLastError()
          Gets the the error (if there is one) from the previous operation on this connection.
 CommandResult getLastError(int w, int wtimeout, boolean fsync)
           
 CommandResult getLastError(WriteConcern concern)
           
 Mongo getMongo()
          Gets the Mongo instance
 String getName()
          Returns the name of this database.
 int getOptions()
          Gets the query options
 CommandResult getPreviousError()
          Returns the last error that occurred since start of database or a call to resetError() The return object will look like
 ReadPreference getReadPreference()
          Gets the default read preference
 DB getSisterDB(String name)
          Gets another database on same server
 CommandResult getStats()
          Returns the result of "dbstats" command
 WriteConcern getWriteConcern()
          Gets the write concern for this database.
 boolean isAuthenticated()
          Returns true if a user has been authenticated
 WriteResult removeUser(String username)
          Removes a user for this db
abstract  void requestDone()
          ends the current "consistent request"
abstract  void requestEnsureConnection()
          ensure that a connection is assigned to the current "consistent request" (from primary pool, if connected to a replica set)
abstract  void requestStart()
          starts a new "consistent request".
 void resetError()
          Resets the error memory for this database.
 void resetOptions()
          Resets the query options
 void setOptions(int options)
          Sets the query options
 void setReadOnly(Boolean b)
          Makes this database read-only.
 void setReadPreference(ReadPreference preference)
          Sets the read preference for this database.
 void setWriteConcern(WriteConcern concern)
          Sets the write concern for this database.
 void slaveOk()
          Deprecated. Replaced with ReadPreference.secondaryPreferred()
 String toString()
          Returns the name of this database.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

_readOnly

protected boolean _readOnly
Constructor Detail

DB

public DB(Mongo mongo,
          String name)
Parameters:
mongo - the mongo instance
name - the database name
Method Detail

requestStart

public abstract void requestStart()
starts a new "consistent request". Following this call and until requestDone() is called, all db operations should use the same underlying connection. This is useful to ensure that operations happen in a certain order with predictable results.


requestDone

public abstract void requestDone()
ends the current "consistent request"


requestEnsureConnection

public abstract void requestEnsureConnection()
ensure that a connection is assigned to the current "consistent request" (from primary pool, if connected to a replica set)


doGetCollection

protected abstract DBCollection doGetCollection(String name)
Returns the collection represented by the string <dbName>.<collectionName>.

Parameters:
name - the name of the collection
Returns:
the collection

getCollection

public DBCollection getCollection(String name)
Gets a collection with a given name. If the collection does not exist, a new collection is created.

Parameters:
name - the name of the collection to return
Returns:
the collection

createCollection

public DBCollection createCollection(String name,
                                     DBObject options)
Creates a collection with a given name and options. If the collection does not exist, a new collection is created. Note that if the options parameter is null, the creation will be deferred to when the collection is written to. Possible options:
capped
boolean: if the collection is capped
size
int: collection size (in bytes)
max
int: max number of documents

Parameters:
name - the name of the collection to return
options - options
Returns:
the collection
Throws:
MongoException

getCollectionFromString

public DBCollection getCollectionFromString(String s)
Returns a collection matching a given string.

Parameters:
s - the name of the collection
Returns:
the collection

command

public CommandResult command(DBObject cmd)
Executes a database command. This method calls command(com.mongodb.DBObject, int) with 0 as query option.

Parameters:
cmd - dbobject representing the command to execute
Returns:
result of command from the database
Throws:
MongoException
See Also:
List of Commands
MongoDB Doc Links

command

public CommandResult command(DBObject cmd,
                             DBEncoder encoder)
Executes a database command. This method calls command(com.mongodb.DBObject, int, com.mongodb.DBEncoder) with 0 as query option.

Parameters:
cmd - dbobject representing the command to execute
encoder -
Returns:
result of command from the database
Throws:
MongoException
See Also:
List of Commands
MongoDB Doc Links

command

public CommandResult command(DBObject cmd,
                             int options,
                             DBEncoder encoder)
Executes a database command. This method calls command(com.mongodb.DBObject, int, com.mongodb.ReadPreference, com.mongodb.DBEncoder) with a null readPrefs.

Parameters:
cmd - dbobject representing the command to execute
options - query options to use
encoder -
Returns:
result of command from the database
Throws:
MongoException
See Also:
List of Commands
MongoDB Doc Links

command

public CommandResult command(DBObject cmd,
                             int options,
                             ReadPreference readPrefs)
Executes a database command. This method calls command(com.mongodb.DBObject, int, com.mongodb.ReadPreference, com.mongodb.DBEncoder) with a default encoder.

Parameters:
cmd - dbobject representing the command to execute
options - query options to use
readPrefs - ReadPreferences for this command (nodes selection is the biggest part of this)
Returns:
result of command from the database
Throws:
MongoException
See Also:
List of Commands
MongoDB Doc Links

command

public CommandResult command(DBObject cmd,
                             int options,
                             ReadPreference readPrefs,
                             DBEncoder encoder)
Executes a database command.

Parameters:
cmd - dbobject representing the command to execute
options - query options to use
readPrefs - ReadPreferences for this command (nodes selection is the biggest part of this)
encoder -
Returns:
result of command from the database
Throws:
MongoException
See Also:
List of Commands
MongoDB Doc Links

command

public CommandResult command(DBObject cmd,
                             int options)
Executes a database command.

Parameters:
cmd - dbobject representing the command to execute
options - query options to use
Returns:
result of command from the database
Throws:
MongoException
See Also:
List of Commands
MongoDB Doc Links

command

public CommandResult command(String cmd)
Executes a database command. This method constructs a simple dbobject and calls command(com.mongodb.DBObject)

Parameters:
cmd - command to execute
Returns:
result of command from the database
Throws:
MongoException
See Also:
List of Commands
MongoDB Doc Links

command

public CommandResult command(String cmd,
                             int options)
Executes a database command. This method constructs a simple dbobject and calls command(com.mongodb.DBObject, int)

Parameters:
cmd - command to execute
options - query options to use
Returns:
result of command from the database
Throws:
MongoException
See Also:
List of Commands
MongoDB Doc Links

doEval

public CommandResult doEval(String code,
                            Object... args)
evaluates a function on the database. This is useful if you need to touch a lot of data lightly, in which case network transfer could be a bottleneck.

Parameters:
code - the function in javascript code
args - arguments to be passed to the function
Returns:
The command result
Throws:
MongoException

eval

public Object eval(String code,
                   Object... args)
calls doEval(java.lang.String, java.lang.Object[]). If the command is successful, the "retval" field is extracted and returned. Otherwise an exception is thrown.

Parameters:
code - the function in javascript code
args - arguments to be passed to the function
Returns:
The object
Throws:
MongoException

getStats

public CommandResult getStats()
Returns the result of "dbstats" command

Returns:
Throws:
MongoException

getName

public String getName()
Returns the name of this database.

Returns:
the name

setReadOnly

public void setReadOnly(Boolean b)
Makes this database read-only. Important note: this is a convenience setting that is only known on the client side and not persisted.

Parameters:
b - if the database should be read-only

getCollectionNames

public Set<String> getCollectionNames()
Returns a set containing the names of all collections in this database.

Returns:
the names of collections in this database
Throws:
MongoException

collectionExists

public boolean collectionExists(String collectionName)
Checks to see if a collection by name %lt;name> exists.

Parameters:
collectionName - The collection to test for existence
Returns:
false if no collection by that name exists, true if a match to an existing collection was found
Throws:
MongoException

toString

public String toString()
Returns the name of this database.

Overrides:
toString in class Object
Returns:
the name

getLastError

public CommandResult getLastError()
Gets the the error (if there is one) from the previous operation on this connection. The result of this command will look like
 { "err" :  errorMessage  , "ok" : 1.0 }
 
The value for errorMessage will be null if no error occurred, or a description otherwise. Important note: when calling this method directly, it is undefined which connection "getLastError" is called on. You may need to explicitly use a "consistent Request", see requestStart() For most purposes it is better not to call this method directly but instead use WriteConcern

Returns:
DBObject with error and status information
Throws:
MongoException

getLastError

public CommandResult getLastError(WriteConcern concern)
Parameters:
concern - the concern associated with "getLastError" call
Returns:
Throws:
MongoException
See Also:
DB#getLastError() }

getLastError

public CommandResult getLastError(int w,
                                  int wtimeout,
                                  boolean fsync)
Parameters:
w -
wtimeout -
fsync -
Returns:
The command result
Throws:
MongoException
See Also:
DB#getLastError(com.mongodb.WriteConcern) }

setWriteConcern

public void setWriteConcern(WriteConcern concern)
Sets the write concern for this database. It Will be used for writes to any collection in this database. See the documentation for WriteConcern for more information.

Parameters:
concern - write concern to use

getWriteConcern

public WriteConcern getWriteConcern()
Gets the write concern for this database.

Returns:

setReadPreference

public void setReadPreference(ReadPreference preference)
Sets the read preference for this database. Will be used as default for reads from any collection in this database. See the documentation for ReadPreference for more information.

Parameters:
preference - Read Preference to use

getReadPreference

public ReadPreference getReadPreference()
Gets the default read preference

Returns:

dropDatabase

public void dropDatabase()
Drops this database. Removes all data on disk. Use with caution.

Throws:
MongoException

isAuthenticated

public boolean isAuthenticated()
Returns true if a user has been authenticated

Returns:
true if authenticated, false otherwise
MongoDB Doc Links

authenticate

public boolean authenticate(String username,
                            char[] password)
Authenticates to db with the given credentials. If this method (or authenticateCommand has already been called with the same credentials and the authentication test succeeded, this method will return true. If this method has already been called with different credentials and the authentication test succeeded, this method will throw an IllegalStateException. If this method has already been called with any credentials and the authentication test failed, this method will re-try the authentication test with the given credentials.

Parameters:
username - name of user for this database
password - password of user for this database
Returns:
true if authenticated, false otherwise
Throws:
MongoException - if authentication failed due to invalid user/pass, or other exceptions like I/O
IllegalStateException - if authentiation test has already succeeded with different credentials
See Also:
authenticateCommand(String, char[])
MongoDB Doc Links

authenticateCommand

public CommandResult authenticateCommand(String username,
                                         char[] password)
Authenticates to db with the given credentials. If this method (or authenticate has already been called with the same credentials and the authentication test succeeded, this method will return true. If this method has already been called with different credentials and the authentication test succeeded, this method will throw an IllegalStateException. If this method has already been called with any credentials and the authentication test failed, this method will re-try the authentication test with the given credentials.

Parameters:
username - name of user for this database
password - password of user for this database
Returns:
the CommandResult from authenticate command
Throws:
MongoException - if authentication failed due to invalid user/pass, or other exceptions like I/O
IllegalStateException - if authentiation test has already succeeded with different credentials
See Also:
authenticate(String, char[])
MongoDB Doc Links

addUser

public WriteResult addUser(String username,
                           char[] passwd)
Adds a new user for this db

Parameters:
username -
passwd -
Throws:
MongoException

addUser

public WriteResult addUser(String username,
                           char[] passwd,
                           boolean readOnly)
Adds a new user for this db

Parameters:
username -
passwd -
readOnly - if true, user will only be able to read
Throws:
MongoException

removeUser

public WriteResult removeUser(String username)
Removes a user for this db

Parameters:
username -
Throws:
MongoException

getPreviousError

public CommandResult getPreviousError()
Returns the last error that occurred since start of database or a call to resetError() The return object will look like
 { err : errorMessage, nPrev : countOpsBack, ok : 1 }
  
The value for errorMessage will be null of no error has occurred, otherwise the error message. The value of countOpsBack will be the number of operations since the error occurred. Care must be taken to ensure that calls to getPreviousError go to the same connection as that of the previous operation. See requestStart() for more information.

Returns:
DBObject with error and status information
Throws:
MongoException

resetError

public void resetError()
Resets the error memory for this database. Used to clear all errors such that getPreviousError() will return no error.

Throws:
MongoException

forceError

public void forceError()
For testing purposes only - this method forces an error to help test error handling

Throws:
MongoException

getMongo

public Mongo getMongo()
Gets the Mongo instance

Returns:

getSisterDB

public DB getSisterDB(String name)
Gets another database on same server

Parameters:
name - name of the database
Returns:

slaveOk

@Deprecated
public void slaveOk()
Deprecated. Replaced with ReadPreference.secondaryPreferred()

Makes it possible to execute "read" queries on a slave node

See Also:
ReadPreference.secondaryPreferred()

addOption

public void addOption(int option)
Adds the give option

Parameters:
option -

setOptions

public void setOptions(int options)
Sets the query options

Parameters:
options -

resetOptions

public void resetOptions()
Resets the query options


getOptions

public int getOptions()
Gets the query options

Returns:

cleanCursors

public abstract void cleanCursors(boolean force)