public abstract class DBCollection extends Object
A typical invocation sequence is thus
MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017));
DB db = mongo.getDB("mydb");
DBCollection collection = db.getCollection("test");
To get a collection to use, just specify the name of the collection to the getCollection(String collectionName) method:
DBCollection coll = db.getCollection("testCollection");
Once you have the collection object, you can insert documents into the collection:
BasicDBObject doc = new BasicDBObject("name", "MongoDB").append("type", "database")
.append("count", 1)
.append("info", new BasicDBObject("x", 203).append("y", 102));
coll.insert(doc);
To show that the document we inserted in the previous step is there, we can do a simple findOne() operation to get the first document in
the collection:
DBObject myDoc = coll.findOne();
System.out.println(myDoc);
Modifier and Type | Field and Description |
---|---|
protected String |
_fullName
Deprecated.
Please use
getFullName() instead. |
protected List<DBObject> |
_hintFields
Deprecated.
Please use
setHintFields(java.util.List) and getHintFields() instead. |
protected String |
_name
Deprecated.
Please use
getName() instead. |
protected Class |
_objectClass
Deprecated.
Please use
getObjectClass() and setObjectClass(Class) instead. |
Modifier | Constructor and Description |
---|---|
protected |
DBCollection(DB base,
String name)
Initializes a new collection.
|
Modifier and Type | Method and Description |
---|---|
protected DBObject |
_checkObject(DBObject o,
boolean canBeNull,
boolean query)
Deprecated.
This method should not be a part of API.
If you override one of the
DBCollection methods please rely on superclass
implementation in checking argument correctness and validity. |
void |
addOption(int option)
Adds the given flag to the default query options.
|
AggregationOutput |
aggregate(DBObject firstOp,
DBObject... additionalOps)
Deprecated.
Use
aggregate(java.util.List) instead |
AggregationOutput |
aggregate(List<DBObject> pipeline)
Method implements aggregation framework.
|
Cursor |
aggregate(List<DBObject> pipeline,
AggregationOptions options)
Method implements aggregation framework.
|
abstract Cursor |
aggregate(List<DBObject> pipeline,
AggregationOptions options,
ReadPreference readPreference)
Method implements aggregation framework.
|
AggregationOutput |
aggregate(List<DBObject> pipeline,
ReadPreference readPreference)
Method implements aggregation framework.
|
Object |
apply(DBObject document)
Deprecated.
This method will be removed in a future release. There is no replacement.
|
Object |
apply(DBObject document,
boolean ensureId)
Deprecated.
This method will be removed in a future release. There is no replacement.
|
protected boolean |
checkReadOnly(boolean strict)
Deprecated.
|
long |
count()
Get the number of documents in the collection.
|
long |
count(DBObject query)
Get the count of documents in collection that would match a criteria.
|
long |
count(DBObject query,
ReadPreference readPrefs)
Get the count of documents in collection that would match a criteria.
|
void |
createIndex(DBObject keys)
Forces creation of an index on a set of fields with the default options, if one does not already exist.
|
void |
createIndex(DBObject keys,
DBObject options)
Forces creation of an index on a set of fields, if one does not already exist.
|
abstract void |
createIndex(DBObject keys,
DBObject options,
DBEncoder encoder)
Deprecated.
use
createIndex(DBObject, com.mongodb.DBObject) the encoder is not used. |
void |
createIndex(DBObject keys,
String name)
Forces creation of an index on a set of fields, if one does not already exist.
|
void |
createIndex(DBObject keys,
String name,
boolean unique)
Forces creation of an index on a set of fields, if one does not already exist.
|
void |
createIndex(String name)
Forces creation of an ascending index on a field with the default options.
|
List |
distinct(String key)
Find the distinct values for a specified field across a collection and returns the results in an array.
|
List |
distinct(String key,
DBObject query)
Find the distinct values for a specified field across a collection and returns the results in an array.
|
List |
distinct(String key,
DBObject query,
ReadPreference readPrefs)
Find the distinct values for a specified field across a collection and returns the results in an array.
|
List |
distinct(String key,
ReadPreference readPrefs)
Find the distinct values for a specified field across a collection and returns the results in an array.
|
protected abstract void |
doapply(DBObject document)
Deprecated.
This method will be removed in a future release. There is no replacement.
|
void |
drop()
Drops (deletes) this collection from the database.
|
void |
dropIndex(DBObject keys)
Drops an index from this collection.
|
void |
dropIndex(String indexName)
Drops the index with the given name from this collection.
|
void |
dropIndexes()
Drop all indexes on this collection.
|
void |
dropIndexes(String name)
Drops the index with the given name from this collection.
|
void |
ensureIndex(DBObject keys)
Deprecated.
use
createIndex(DBObject) instead |
void |
ensureIndex(DBObject keys,
DBObject optionsIN)
Deprecated.
use
createIndex(DBObject, DBObject) instead |
void |
ensureIndex(DBObject keys,
String name)
Deprecated.
use
createIndex(DBObject, DBObject) instead |
void |
ensureIndex(DBObject keys,
String name,
boolean unique)
Deprecated.
use
createIndex(DBObject, String, boolean) instead |
void |
ensureIndex(String name)
Deprecated.
use
createIndex(String) instead |
boolean |
equals(Object o) |
CommandResult |
explainAggregate(List<DBObject> pipeline,
AggregationOptions options)
Return the explain plan for the aggregation pipeline.
|
DBCursor |
find()
Queries for all objects in this collection.
|
DBCursor |
find(DBObject ref)
Queries for an object in this collection.
|
DBCursor |
find(DBObject ref,
DBObject keys)
Queries for an object in this collection.
|
DBCursor |
find(DBObject query,
DBObject fields,
int numToSkip,
int batchSize)
Deprecated.
use
DBCursor.skip(int) and DBCursor.batchSize(int) on the DBCursor
returned from find(DBObject, DBObject) |
DBCursor |
find(DBObject query,
DBObject fields,
int numToSkip,
int batchSize,
int options)
Deprecated.
use
DBCursor.skip(int) , DBCursor.batchSize(int) and DBCursor.setOptions(int) on the DBCursor returned from find(DBObject,
DBObject) |
DBObject |
findAndModify(DBObject query,
DBObject update)
Atomically modify and return a single document.
|
DBObject |
findAndModify(DBObject query,
DBObject sort,
DBObject update)
Atomically modify and return a single document.
|
DBObject |
findAndModify(DBObject query,
DBObject fields,
DBObject sort,
boolean remove,
DBObject update,
boolean returnNew,
boolean upsert)
Atomically modify and return a single document.
|
DBObject |
findAndModify(DBObject query,
DBObject fields,
DBObject sort,
boolean remove,
DBObject update,
boolean returnNew,
boolean upsert,
long maxTime,
TimeUnit maxTimeUnit)
Atomically modify and return a single document.
|
DBObject |
findAndRemove(DBObject query)
Atomically modify and return a single document.
|
DBObject |
findOne()
Returns a single object from this collection.
|
DBObject |
findOne(DBObject o)
Returns a single object from this collection matching the query.
|
DBObject |
findOne(DBObject o,
DBObject fields)
Returns a single object from this collection matching the query.
|
DBObject |
findOne(DBObject o,
DBObject fields,
DBObject orderBy)
Returns a single object from this collection matching the query.
|
DBObject |
findOne(DBObject o,
DBObject fields,
DBObject orderBy,
ReadPreference readPref)
Get a single document from collection.
|
DBObject |
findOne(DBObject o,
DBObject fields,
ReadPreference readPref)
Get a single document from collection.
|
DBObject |
findOne(Object id)
Get a single document from collection by '_id'.
|
DBObject |
findOne(Object id,
DBObject projection)
Get a single document from collection by '_id'.
|
static String |
genIndexName(DBObject keys)
Deprecated.
This method is NOT a part of public API and will be dropped in 3.x versions.
|
DBCollection |
getCollection(String n)
Find a collection that is prefixed with this collection's name.
|
long |
getCount()
Get the count of documents in a collection.
|
long |
getCount(DBObject query)
Get the count of documents in collection that would match a criteria.
|
long |
getCount(DBObject query,
DBObject fields)
Get the count of documents in collection that would match a criteria.
|
long |
getCount(DBObject query,
DBObject fields,
long limit,
long skip)
Get the count of documents in collection that would match a criteria.
|
long |
getCount(DBObject query,
DBObject fields,
long limit,
long skip,
ReadPreference readPrefs)
Get the count of documents in collection that would match a criteria.
|
long |
getCount(DBObject query,
DBObject fields,
ReadPreference readPrefs)
Get the count of documents in collection that would match a criteria.
|
long |
getCount(ReadPreference readPrefs)
Get the count of documents in a collection.
|
DB |
getDB()
Returns the database this collection is a member of.
|
DBDecoderFactory |
getDBDecoderFactory()
Get the decoder factory for this collection.
|
DBEncoderFactory |
getDBEncoderFactory()
Get the encoder factory for this collection.
|
String |
getFullName()
Get the full name of a collection, with the database name as a prefix.
|
protected List<DBObject> |
getHintFields()
Get hint fields for this collection (used to optimize queries).
|
abstract List<DBObject> |
getIndexInfo()
Return a list of the indexes for this collection.
|
protected Class |
getInternalClass(String path)
Gets the internal class for the given path in the document hierarchy
|
String |
getName()
Get the name of a collection.
|
Class |
getObjectClass()
Gets the default class for objects in the collection
|
int |
getOptions()
Gets the default query options
|
ReadPreference |
getReadPreference()
Gets the
ReadPreference . |
CommandResult |
getStats()
The collStats command returns a variety of storage statistics for a given collection
|
WriteConcern |
getWriteConcern()
Get the
WriteConcern for this collection. |
DBObject |
group(DBObject args)
Deprecated.
use
group(com.mongodb.GroupCommand) instead. This method will be removed in 3.0 |
DBObject |
group(DBObject key,
DBObject cond,
DBObject initial,
String reduce)
Group documents in a collection by the specified key and performs simple aggregation functions such as computing counts and sums.
|
DBObject |
group(DBObject key,
DBObject cond,
DBObject initial,
String reduce,
String finalize)
Group documents in a collection by the specified key and performs simple aggregation functions such as computing counts and sums.
|
DBObject |
group(DBObject key,
DBObject cond,
DBObject initial,
String reduce,
String finalize,
ReadPreference readPrefs)
Group documents in a collection by the specified key and performs simple aggregation functions such as computing counts and sums.
|
DBObject |
group(GroupCommand cmd)
Group documents in a collection by the specified key and performs simple aggregation functions such as computing counts and sums.
|
DBObject |
group(GroupCommand cmd,
ReadPreference readPrefs)
Group documents in a collection by the specified key and performs simple aggregation functions such as computing counts and sums.
|
int |
hashCode() |
BulkWriteOperation |
initializeOrderedBulkOperation()
Creates a builder for an ordered bulk write operation, consisting of an ordered collection of write requests, which can be any
combination of inserts, updates, replaces, or removes.
|
BulkWriteOperation |
initializeUnorderedBulkOperation()
Creates a builder for an unordered bulk operation, consisting of an unordered collection of write requests, which can be any
combination of inserts, updates, replaces, or removes.
|
WriteResult |
insert(DBObject... arr)
Insert documents into a collection.
|
WriteResult |
insert(DBObject[] arr,
WriteConcern concern)
Insert documents into a collection.
|
WriteResult |
insert(DBObject[] arr,
WriteConcern concern,
DBEncoder encoder)
Insert documents into a collection.
|
WriteResult |
insert(DBObject o,
WriteConcern concern)
Insert a document into a collection.
|
WriteResult |
insert(List<DBObject> list)
Insert documents into a collection.
|
WriteResult |
insert(List<DBObject> documents,
InsertOptions insertOptions)
Insert documents into a collection.
|
WriteResult |
insert(List<DBObject> list,
WriteConcern concern)
Insert documents into a collection.
|
abstract WriteResult |
insert(List<DBObject> list,
WriteConcern concern,
DBEncoder encoder)
Insert documents into a collection.
|
WriteResult |
insert(WriteConcern concern,
DBObject... arr)
Insert documents into a collection.
|
boolean |
isCapped()
Checks whether this collection is capped
|
MapReduceOutput |
mapReduce(DBObject command)
Deprecated.
Use
mapReduce(MapReduceCommand) instead |
MapReduceOutput |
mapReduce(MapReduceCommand command)
Allows you to run map-reduce aggregation operations over a collection and saves to a named collection.
|
MapReduceOutput |
mapReduce(String map,
String reduce,
String outputTarget,
DBObject query)
Allows you to run map-reduce aggregation operations over a collection.
|
MapReduceOutput |
mapReduce(String map,
String reduce,
String outputTarget,
MapReduceCommand.OutputType outputType,
DBObject query)
Allows you to run map-reduce aggregation operations over a collection and saves to a named collection.
|
MapReduceOutput |
mapReduce(String map,
String reduce,
String outputTarget,
MapReduceCommand.OutputType outputType,
DBObject query,
ReadPreference readPrefs)
Allows you to run map-reduce aggregation operations over a collection and saves to a named collection.
|
abstract List<Cursor> |
parallelScan(ParallelScanOptions options)
Return a list of cursors over the collection that can be used to scan it in parallel.
|
WriteResult |
remove(DBObject o)
Remove documents from a collection.
|
WriteResult |
remove(DBObject o,
WriteConcern concern)
Remove documents from a collection.
|
abstract WriteResult |
remove(DBObject o,
WriteConcern concern,
DBEncoder encoder)
Remove documents from a collection.
|
DBCollection |
rename(String newName)
Calls
rename(java.lang.String, boolean) with dropTarget=false |
DBCollection |
rename(String newName,
boolean dropTarget)
Renames of this collection to newName
|
void |
resetIndexCache()
Deprecated.
This will be removed in 3.0
|
void |
resetOptions()
Resets the default query options
|
WriteResult |
save(DBObject jo)
Update an existing document or insert a document depending on the parameter.
|
WriteResult |
save(DBObject jo,
WriteConcern concern)
Update an existing document or insert a document depending on the parameter.
|
void |
setDBDecoderFactory(DBDecoderFactory fact)
Set a customer decoder factory for this collection.
|
void |
setDBEncoderFactory(DBEncoderFactory fact)
Set a customer encoder factory for this collection.
|
void |
setHintFields(List<DBObject> indexes)
Override MongoDB's default index selection and query optimization process.
|
void |
setInternalClass(String path,
Class c)
Sets the internal class for the given path in the document hierarchy
|
void |
setObjectClass(Class c)
Sets a default class for objects in this collection; null resets the class to nothing.
|
void |
setOptions(int options)
Sets the default query options, overwriting previous value.
|
void |
setReadPreference(ReadPreference preference)
Sets the
ReadPreference for this collection. |
void |
setWriteConcern(WriteConcern writeConcern)
Set the
WriteConcern for this collection. |
void |
slaveOk()
Deprecated.
Replaced with
ReadPreference.secondaryPreferred() |
String |
toString() |
WriteResult |
update(DBObject q,
DBObject o)
Modify an existing document or documents in collection.
|
WriteResult |
update(DBObject q,
DBObject o,
boolean upsert,
boolean multi)
Modify an existing document or documents in collection.
|
WriteResult |
update(DBObject q,
DBObject o,
boolean upsert,
boolean multi,
WriteConcern concern)
Modify an existing document or documents in collection.
|
abstract WriteResult |
update(DBObject q,
DBObject o,
boolean upsert,
boolean multi,
WriteConcern concern,
DBEncoder encoder)
Modify an existing document or documents in collection.
|
WriteResult |
updateMulti(DBObject q,
DBObject o)
Modify documents in collection.
|
@Deprecated protected final String _name
getName()
instead.@Deprecated protected final String _fullName
getFullName()
instead.@Deprecated protected List<DBObject> _hintFields
setHintFields(java.util.List)
and getHintFields()
instead.@Deprecated protected Class _objectClass
getObjectClass()
and setObjectClass(Class)
instead.public WriteResult insert(DBObject[] arr, WriteConcern concern)
arr
- DBObject
's to be insertedconcern
- WriteConcern
to be used during operationMongoException
- if the operation failspublic WriteResult insert(DBObject[] arr, WriteConcern concern, DBEncoder encoder)
arr
- DBObject
's to be insertedconcern
- WriteConcern
to be used during operationencoder
- DBEncoder
to be usedMongoException
- if the operation failspublic WriteResult insert(DBObject o, WriteConcern concern)
o
- DBObject
to be insertedconcern
- WriteConcern
to be used during operationMongoException
- if the operation failspublic WriteResult insert(DBObject... arr)
WriteConcern
will be used.arr
- DBObject
's to be insertedMongoException
- if the operation failspublic WriteResult insert(WriteConcern concern, DBObject... arr)
arr
- DBObject
's to be insertedconcern
- WriteConcern
to be used during operationMongoException
- if the operation failspublic WriteResult insert(List<DBObject> list)
list
- list of DBObject
to be insertedMongoException
- if the operation failspublic WriteResult insert(List<DBObject> list, WriteConcern concern)
list
- list of DBObject
's to be insertedconcern
- WriteConcern
to be used during operationMongoException
- if the operation failspublic abstract WriteResult insert(List<DBObject> list, WriteConcern concern, DBEncoder encoder)
list
- a list of DBObject
's to be insertedconcern
- WriteConcern
to be used during operationencoder
- DBEncoder
to use to serialise the documentsMongoException
- if the operation failspublic WriteResult insert(List<DBObject> documents, InsertOptions insertOptions)
Insert documents into a collection. If the collection does not exists on the server, then it will be created. If the new document does not contain an '_id' field, it will be added.
If the value of the continueOnError property of the given InsertOptions
is true,
that value will override the value of the continueOnError property of the given WriteConcern
. Otherwise,
the value of the continueOnError property of the given WriteConcern
will take effect.
documents
- a list of DBObject
's to be insertedinsertOptions
- the options to use for the insertMongoException
- if the operation failspublic WriteResult update(DBObject q, DBObject o, boolean upsert, boolean multi, WriteConcern concern)
find(DBObject)
.q
- the selection criteria for the updateo
- the modifications to applyupsert
- when true, inserts a document if no document matches the update query criteriamulti
- when true, updates all documents in the collection that match the update query criteria, otherwise only updates oneconcern
- WriteConcern
to be used during operationMongoException
public abstract WriteResult update(DBObject q, DBObject o, boolean upsert, boolean multi, WriteConcern concern, DBEncoder encoder)
find(DBObject)
.q
- the selection criteria for the updateo
- the modifications to applyupsert
- when true, inserts a document if no document matches the update query criteriamulti
- when true, updates all documents in the collection that match the update query criteria, otherwise only updates oneconcern
- WriteConcern
to be used during operationencoder
- the DBEncoder to useMongoException
public WriteResult update(DBObject q, DBObject o, boolean upsert, boolean multi)
find(DBObject)
. Calls update(com.mongodb.DBObject,
com.mongodb.DBObject, boolean, boolean, com.mongodb.WriteConcern)
with default WriteConcern.q
- the selection criteria for the updateo
- the modifications to applyupsert
- when true, inserts a document if no document matches the update query criteriamulti
- when true, updates all documents in the collection that match the update query criteria, otherwise only updates oneMongoException
public WriteResult update(DBObject q, DBObject o)
find(DBObject)
. Calls update(com.mongodb.DBObject,
com.mongodb.DBObject, boolean, boolean)
with upsert=false and multi=falseq
- the selection criteria for the updateo
- the modifications to applyMongoException
public WriteResult updateMulti(DBObject q, DBObject o)
find()
. Calls update(com.mongodb.DBObject,
com.mongodb.DBObject, boolean, boolean)
with upsert=false and multi=trueq
- the selection criteria for the updateo
- the modifications to applyMongoException
@Deprecated protected abstract void doapply(DBObject document)
document
- object to which to add the fieldspublic WriteResult remove(DBObject o, WriteConcern concern)
o
- the deletion criteria using query operators. Omit the query parameter or pass an empty document to delete all
documents in the collection.concern
- WriteConcern
to be used during operationMongoException
public abstract WriteResult remove(DBObject o, WriteConcern concern, DBEncoder encoder)
o
- the deletion criteria using query operators. Omit the query parameter or pass an empty document to delete all
documents in the collection.concern
- WriteConcern
to be used during operationencoder
- DBEncoder
to be usedMongoException
public WriteResult remove(DBObject o)
remove(com.mongodb.DBObject, com.mongodb.WriteConcern)
with the
default WriteConcerno
- the deletion criteria using query operators. Omit the query parameter or pass an empty document to delete all documents in
the collection.MongoException
@Deprecated public DBCursor find(DBObject query, DBObject fields, int numToSkip, int batchSize, int options)
DBCursor.skip(int)
, DBCursor.batchSize(int)
and DBCursor.setOptions(int)
on the DBCursor
returned from find(DBObject,
DBObject)
find(com.mongodb.DBObject, com.mongodb.DBObject, int, int)
and applies the query optionsquery
- query used to searchfields
- the fields of matching objects to returnnumToSkip
- number of objects to skipbatchSize
- the batch size. This option has a complex behavior, see DBCursor.batchSize(int)
options
- see Bytes
QUERYOPTION_*MongoException
@Deprecated public DBCursor find(DBObject query, DBObject fields, int numToSkip, int batchSize)
DBCursor.skip(int)
and DBCursor.batchSize(int)
on the DBCursor
returned from find(DBObject, DBObject)
query
- query used to searchfields
- the fields of matching objects to returnnumToSkip
- number of objects to skipbatchSize
- the batch size. This option has a complex behavior, see DBCursor.batchSize(int)
MongoException
public DBObject findOne(Object id)
id
- value of '_id' field of a document we are looking forpublic DBObject findOne(Object id, DBObject projection)
id
- value of '_id' field of a document we are looking forprojection
- specifies which projection MongoDB will return from the documents in the result set.public DBObject findAndModify(DBObject query, DBObject fields, DBObject sort, boolean remove, DBObject update, boolean returnNew, boolean upsert)
query
- specifies the selection criteria for the modificationfields
- a subset of fields to returnsort
- determines which document the operation will modify if the query selects multiple documentsremove
- when true, removes the selected documentreturnNew
- when true, returns the modified document rather than the originalupdate
- the modifications to applyupsert
- when true, operation creates a new document if the query returns no documentsreturnNew
is true, in which case it returns the document
after the changes were madeMongoException
public DBObject findAndModify(DBObject query, DBObject fields, DBObject sort, boolean remove, DBObject update, boolean returnNew, boolean upsert, long maxTime, TimeUnit maxTimeUnit)
query
- specifies the selection criteria for the modificationfields
- a subset of fields to returnsort
- determines which document the operation will modify if the query selects multiple documentsremove
- when true
, removes the selected documentreturnNew
- when true, returns the modified document rather than the originalupdate
- performs an update of the selected documentupsert
- when true, operation creates a new document if the query returns no documentsmaxTime
- the maximum time that the server will allow this operation to execute before killing it. A non-zero value requires
a server version >= 2.6maxTimeUnit
- the unit that maxTime is specified inreturnNew
is true, in which case it returns the document
after the changes were madepublic DBObject findAndModify(DBObject query, DBObject sort, DBObject update)
findAndModify(com.mongodb.DBObject, com.mongodb.DBObject, com.mongodb.DBObject, boolean,
com.mongodb.DBObject, boolean, boolean)
with fields=null, remove=false, returnNew=false, upsert=falsequery
- specifies the selection criteria for the modificationsort
- determines which document the operation will modify if the query selects multiple documentsupdate
- the modifications to applyMongoException
public DBObject findAndModify(DBObject query, DBObject update)
findAndModify(com.mongodb.DBObject, com.mongodb.DBObject, com.mongodb.DBObject, boolean,
com.mongodb.DBObject, boolean, boolean)
with fields=null, sort=null, remove=false, returnNew=false, upsert=falsequery
- specifies the selection criteria for the modificationupdate
- the modifications to applyMongoException
public DBObject findAndRemove(DBObject query)
findAndModify(com.mongodb.DBObject, com.mongodb.DBObject, com.mongodb.DBObject, boolean,
com.mongodb.DBObject, boolean, boolean)
with fields=null, sort=null, remove=true, returnNew=false, upsert=falsequery
- specifies the selection criteria for the modificationMongoException
public void createIndex(String name)
name
- name of field to index onMongoException
public void createIndex(DBObject keys)
keys
- a document that contains pairs with the name of the field or fields to index and order of the indexMongoException
public void createIndex(DBObject keys, DBObject options)
keys
- a document that contains pairs with the name of the field or fields to index and order of the indexoptions
- a document that controls the creation of the index.MongoException
public void createIndex(DBObject keys, String name)
keys
- a document that contains pairs with the name of the field or fields to index and order of the indexname
- an identifier for the index. If null or empty, the default name will be used.MongoException
public void createIndex(DBObject keys, String name, boolean unique)
keys
- a document that contains pairs with the name of the field or fields to index and order of the indexname
- an identifier for the index. If null or empty, the default name will be used.unique
- if the index should be uniqueMongoException
@Deprecated public abstract void createIndex(DBObject keys, DBObject options, DBEncoder encoder)
createIndex(DBObject, com.mongodb.DBObject)
the encoder is not used.keys
- a document that contains pairs with the name of the field or fields to index and order of the indexoptions
- a document that controls the creation of the index.encoder
- specifies the encoder that used during operationMongoException
@Deprecated public void ensureIndex(String name)
createIndex(String)
insteadname
- name of field to index onMongoException
@Deprecated public void ensureIndex(DBObject keys)
createIndex(DBObject)
insteadensureIndex(com.mongodb.DBObject, com.mongodb.DBObject)
with default optionskeys
- an object with a key set of the fields desired for the indexMongoException
@Deprecated public void ensureIndex(DBObject keys, String name)
createIndex(DBObject, DBObject)
insteadensureIndex(com.mongodb.DBObject, java.lang.String, boolean)
with unique=falsekeys
- fields to use for indexname
- an identifier for the indexMongoException
@Deprecated public void ensureIndex(DBObject keys, String name, boolean unique)
createIndex(DBObject, String, boolean)
insteadkeys
- fields to use for indexname
- an identifier for the index. If null or empty, the default name will be used.unique
- if the index should be uniqueMongoException
@Deprecated public void ensureIndex(DBObject keys, DBObject optionsIN)
createIndex(DBObject, DBObject)
insteadkeys
- an object with a key set of the fields desired for the indexoptionsIN
- options for the index (name, unique, etc)MongoException
@Deprecated public void resetIndexCache()
@Deprecated public static String genIndexName(DBObject keys)
keys
- the names of the fields used in this indexpublic void setHintFields(List<DBObject> indexes)
indexes
- list of indexes to "hint" or force MongoDB to use when performing the query.protected List<DBObject> getHintFields()
DBObject
to be used as hints.public DBCursor find(DBObject ref)
ref
- A document outlining the search querypublic DBCursor find(DBObject ref, DBObject keys)
An empty DBObject will match every document in the collection. Regardless of fields specified, the _id fields are always returned.
An example that returns the "x" and "_id" fields for every document in the collection that has an "x" field:
BasicDBObject keys = new BasicDBObject();
keys.put("x", 1);
DBCursor cursor = collection.find(new BasicDBObject(), keys);
ref
- object for which to searchkeys
- fields to returnpublic DBCursor find()
public DBObject findOne()
null
if the collection is emptyMongoException
public DBObject findOne(DBObject o)
o
- the query objectnull
if no such object existsMongoException
public DBObject findOne(DBObject o, DBObject fields)
o
- the query objectfields
- fields to returnnull
if no such object existsMongoException
public DBObject findOne(DBObject o, DBObject fields, DBObject orderBy)
o
- the query objectfields
- fields to returnorderBy
- fields to order bynull
if no such object existsMongoException
public DBObject findOne(DBObject o, DBObject fields, ReadPreference readPref)
o
- the selection criteria using query operators.fields
- specifies which fields MongoDB will return from the documents in the result set.readPref
- ReadPreference
to be used for this operationnull
if no such object existsMongoException
public DBObject findOne(DBObject o, DBObject fields, DBObject orderBy, ReadPreference readPref)
o
- the selection criteria using query operators.fields
- specifies which projection MongoDB will return from the documents in the result set.orderBy
- A document whose fields specify the attributes on which to sort the result set.readPref
- ReadPreference
to be used for this operationnull
if no such object existsMongoException
@Deprecated public Object apply(DBObject document)
doapply(DBObject)
if you need to add specific fields before
saving object to collection.document
- document to be passed to doapply()
@Deprecated public Object apply(DBObject document, boolean ensureId)
doapply(DBObject)
if you need to add specific fields before
saving object to collection.document
- document to be passed to doapply()
ensureId
- specifies if '_id' field needs to be added to the document in case of absence.public WriteResult save(DBObject jo)
jo
- DBObject
to save to the collection.MongoException
- if the operation failspublic WriteResult save(DBObject jo, WriteConcern concern)
jo
- DBObject
to save to the collection.concern
- WriteConcern
to be used during operationMongoException
- if the operation failspublic void dropIndexes()
MongoException
public void dropIndexes(String name)
dropIndex(indexName)
.name
- name of index to dropMongoException
- if the index does not existpublic void drop()
MongoException
public long count()
MongoException
public long count(DBObject query)
query
- specifies the selection criteriaMongoException
public long count(DBObject query, ReadPreference readPrefs)
query
- specifies the selection criteriareadPrefs
- ReadPreference
to be used for this operationMongoException
public long getCount()
getCount(com.mongodb.DBObject, com.mongodb.DBObject)
with an
empty query and null fields.MongoException
public long getCount(ReadPreference readPrefs)
getCount(com.mongodb.DBObject, com.mongodb.DBObject,
com.mongodb.ReadPreference)
with empty query and null fields.readPrefs
- ReadPreference
to be used for this operationMongoException
public long getCount(DBObject query)
getCount(com.mongodb.DBObject,
com.mongodb.DBObject)
with null fields.query
- specifies the selection criteriaMongoException
public long getCount(DBObject query, DBObject fields)
getCount(com.mongodb.DBObject,
com.mongodb.DBObject, long, long)
with limit=0 and skip=0query
- specifies the selection criteriafields
- this is ignoredMongoException
public long getCount(DBObject query, DBObject fields, ReadPreference readPrefs)
getCount(com.mongodb.DBObject,
com.mongodb.DBObject, long, long, com.mongodb.ReadPreference)
with limit=0 and skip=0query
- specifies the selection criteriafields
- this is ignoredreadPrefs
- ReadPreference
to be used for this operationMongoException
public long getCount(DBObject query, DBObject fields, long limit, long skip)
getCount(com.mongodb.DBObject,
com.mongodb.DBObject, long, long, com.mongodb.ReadPreference)
with the DBCollection's ReadPreferencequery
- specifies the selection criteriafields
- this is ignoredlimit
- limit the count to this valueskip
- number of documents to skipMongoException
public long getCount(DBObject query, DBObject fields, long limit, long skip, ReadPreference readPrefs)
query
- specifies the selection criteriafields
- this is ignoredlimit
- limit the count to this valueskip
- number of documents to skipreadPrefs
- ReadPreference
to be used for this operationMongoException
public DBCollection rename(String newName)
rename(java.lang.String, boolean)
with dropTarget=falsenewName
- new collection name (not a full namespace)MongoException
public DBCollection rename(String newName, boolean dropTarget)
newName
- new collection name (not a full namespace)dropTarget
- if a collection with the new name exists, whether or not to drop itMongoException
public DBObject group(DBObject key, DBObject cond, DBObject initial, String reduce)
SELECT ... GROUP BY
statement in SQL. Calls group(com.mongodb.DBObject,
com.mongodb.DBObject, com.mongodb.DBObject, java.lang.String, java.lang.String)
with finalize=nullkey
- specifies one or more document fields to groupcond
- specifies the selection criteria to determine which documents in the collection to processinitial
- initializes the aggregation result documentreduce
- specifies an $reduce Javascript function, that operates on the documents during the grouping operationMongoException
public DBObject group(DBObject key, DBObject cond, DBObject initial, String reduce, String finalize)
SELECT ... GROUP BY
statement in SQL.key
- specifies one or more document fields to groupcond
- specifies the selection criteria to determine which documents in the collection to processinitial
- initializes the aggregation result documentreduce
- specifies an $reduce Javascript function, that operates on the documents during the grouping operationfinalize
- specifies a Javascript function that runs each item in the result set before final value will be returnedMongoException
public DBObject group(DBObject key, DBObject cond, DBObject initial, String reduce, String finalize, ReadPreference readPrefs)
SELECT ... GROUP BY
statement in SQL.key
- specifies one or more document fields to groupcond
- specifies the selection criteria to determine which documents in the collection to processinitial
- initializes the aggregation result documentreduce
- specifies an $reduce Javascript function, that operates on the documents during the grouping operationfinalize
- specifies a Javascript function that runs each item in the result set before final value will be returnedreadPrefs
- ReadPreference
to be used for this operationMongoException
public DBObject group(GroupCommand cmd)
SELECT ... GROUP BY
statement in SQL.cmd
- the group command containing the details of how to perform the operation.MongoException
public DBObject group(GroupCommand cmd, ReadPreference readPrefs)
SELECT ... GROUP BY
statement in SQL.cmd
- the group command containing the details of how to perform the operation.readPrefs
- ReadPreference
to be used for this operationMongoException
@Deprecated public DBObject group(DBObject args)
group(com.mongodb.GroupCommand)
instead. This method will be removed in 3.0SELECT ... GROUP BY
statement in SQL.args
- object representing the arguments to the group functionMongoException
public List distinct(String key)
key
- Specifies the field for which to return the distinct valuesList
of the distinct valuesMongoException
public List distinct(String key, ReadPreference readPrefs)
key
- Specifies the field for which to return the distinct valuesreadPrefs
- ReadPreference
to be used for this operationList
of the distinct valuesMongoException
public List distinct(String key, DBObject query)
key
- Specifies the field for which to return the distinct valuesquery
- specifies the selection query to determine the subset of documents from which to retrieve the distinct valuesList
of the distinct valuesMongoException
public List distinct(String key, DBObject query, ReadPreference readPrefs)
key
- Specifies the field for which to return the distinct valuesquery
- specifies the selection query to determine the subset of documents from which to retrieve the distinct valuesreadPrefs
- ReadPreference
to be used for this operationList
of the distinct valuesMongoException
public MapReduceOutput mapReduce(String map, String reduce, String outputTarget, DBObject query)
map
- a JavaScript function that associates or "maps" a value with a key and emits the key and value pair.reduce
- a JavaScript function that "reduces" to a single object all the values associated with a particular key.outputTarget
- specifies the location of the result of the map-reduce operation (optional) - leave null if want to use temp
collectionquery
- specifies the selection criteria using query operators for determining the documents input to the map
function.MongoException
public MapReduceOutput mapReduce(String map, String reduce, String outputTarget, MapReduceCommand.OutputType outputType, DBObject query)
map
- a JavaScript function that associates or "maps" a value with a key and emits the key and value pair.reduce
- a JavaScript function that "reduces" to a single object all the values associated with a particular key.outputTarget
- specifies the location of the result of the map-reduce operation (optional) - leave null if want to use temp
collectionoutputType
- specifies the type of job outputquery
- specifies the selection criteria using query operators for determining the documents input to the map function.MongoException
public MapReduceOutput mapReduce(String map, String reduce, String outputTarget, MapReduceCommand.OutputType outputType, DBObject query, ReadPreference readPrefs)
map
- a JavaScript function that associates or "maps" a value with a key and emits the key and value pair.reduce
- a JavaScript function that "reduces" to a single object all the values associated with a particular key.outputTarget
- specifies the location of the result of the map-reduce operation (optional) - leave null if want to use temp
collectionoutputType
- specifies the type of job outputquery
- specifies the selection criteria using query operators for determining the documents input to the map
function.readPrefs
- the read preference specifying where to run the query. Only applied for Inline output typeMongoException
public MapReduceOutput mapReduce(MapReduceCommand command)
command
- object representing the parameters to the operationMongoException
@Deprecated public MapReduceOutput mapReduce(DBObject command)
mapReduce(MapReduceCommand)
insteadcommand
- document representing the parameters to this operation.MongoException
@Deprecated public AggregationOutput aggregate(DBObject firstOp, DBObject... additionalOps)
aggregate(java.util.List)
insteadfirstOp
- requisite first operation to be performed in the aggregation pipelineadditionalOps
- additional operations to be performed in the aggregation pipelinepublic AggregationOutput aggregate(List<DBObject> pipeline)
pipeline
- operations to be performed in the aggregation pipelinepublic AggregationOutput aggregate(List<DBObject> pipeline, ReadPreference readPreference)
pipeline
- operations to be performed in the aggregation pipelinereadPreference
- the read preference specifying where to run the querypublic Cursor aggregate(List<DBObject> pipeline, AggregationOptions options)
pipeline
- operations to be performed in the aggregation pipelineoptions
- options to apply to the aggregationpublic abstract Cursor aggregate(List<DBObject> pipeline, AggregationOptions options, ReadPreference readPreference)
pipeline
- operations to be performed in the aggregation pipelineoptions
- options to apply to the aggregationreadPreference
- ReadPreference
to be used for this operationpublic CommandResult explainAggregate(List<DBObject> pipeline, AggregationOptions options)
pipeline
- the aggregation pipeline to explainoptions
- the options to apply to the aggregationpublic abstract List<Cursor> parallelScan(ParallelScanOptions options)
Return a list of cursors over the collection that can be used to scan it in parallel.
Note: As of MongoDB 2.6, this method will work against a mongod, but not a mongos.
options
- the parallel scan optionspublic BulkWriteOperation initializeOrderedBulkOperation()
Creates a builder for an ordered bulk write operation, consisting of an ordered collection of write requests, which can be any combination of inserts, updates, replaces, or removes. Write requests included in the bulk operations will be executed in order, and will halt on the first failure.
Note: While this bulk write operation will execute on MongoDB 2.4 servers and below, the writes will be performed one at a time, as that is the only way to preserve the semantics of the value returned from execution or the exception thrown.
Note: While a bulk write operation with a mix of inserts, updates, replaces, and removes is supported, the implementation will batch up consecutive requests of the same type and send them to the server one at a time. For example, if a bulk write operation consists of 10 inserts followed by 5 updates, followed by 10 more inserts, it will result in three round trips to the server.
public BulkWriteOperation initializeUnorderedBulkOperation()
Creates a builder for an unordered bulk operation, consisting of an unordered collection of write requests, which can be any combination of inserts, updates, replaces, or removes. Write requests included in the bulk operation will be executed in an undefined order, and all requests will be executed even if some fail.
Note: While this bulk write operation will execute on MongoDB 2.4 servers and below, the writes will be performed one at a time, as that is the only way to preserve the semantics of the value returned from execution or the exception thrown.
public abstract List<DBObject> getIndexInfo()
MongoException
public void dropIndex(DBObject keys)
keys
- the specification of the index to dropMongoException
- if the index does not existpublic void dropIndex(String indexName)
indexName
- name of index to dropMongoException
- if the index does not existpublic CommandResult getStats()
public boolean isCapped()
MongoException
@Deprecated protected DBObject _checkObject(DBObject o, boolean canBeNull, boolean query)
DBCollection
methods please rely on superclass
implementation in checking argument correctness and validity.public DBCollection getCollection(String n)
DBCollection users = mongo.getCollection( "wiki" ).getCollection( "users" );
Which is equivalent to
DBCollection users = mongo.getCollection( "wiki.users" );
n
- the name of the collection to findpublic String getName()
public String getFullName()
public DB getDB()
@Deprecated protected boolean checkReadOnly(boolean strict)
DB.setReadOnly(Boolean)
strict
- if an exception should be thrown if the database is read-onlyRuntimeException
- if the database is read-only and strict
is setpublic void setObjectClass(Class c)
c
- the classIllegalArgumentException
- if c
is not a DBObjectpublic Class getObjectClass()
public void setInternalClass(String path, Class c)
path
- the path to map the given Class toc
- the Class to map the given path toprotected Class getInternalClass(String path)
path
- the path to map the given Class topublic void setWriteConcern(WriteConcern writeConcern)
WriteConcern
for this collection. Will be used for writes to this collection. Overrides any setting of write concern
at the DB level.writeConcern
- WriteConcern to usepublic WriteConcern getWriteConcern()
WriteConcern
for this collection.public void setReadPreference(ReadPreference preference)
ReadPreference
for this collection. Will be used as default for reads from this collection; overrides DB and
Connection level settings. See the documentation for ReadPreference
for more information.preference
- ReadPreference to usepublic ReadPreference getReadPreference()
ReadPreference
.@Deprecated public void slaveOk()
ReadPreference.secondaryPreferred()
public void addOption(int option)
option
- value to be addedpublic void setOptions(int options)
options
- bit vector of query optionspublic void resetOptions()
public int getOptions()
public void setDBDecoderFactory(DBDecoderFactory fact)
fact
- the factory to set.public DBDecoderFactory getDBDecoderFactory()
public void setDBEncoderFactory(DBEncoderFactory fact)
fact
- the factory to set.public DBEncoderFactory getDBEncoderFactory()