@ThreadSafe public class DBCollection extends java.lang.Object
MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017));
DB db = mongoClient.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);
See Mongo.getDB(String)
for further information about the effective deprecation of this class.Modifier and Type | Field and Description |
---|---|
static java.lang.String |
ID_FIELD_NAME |
Modifier and Type | Method and Description |
---|---|
void |
addOption(int option)
Adds the given flag to the default query options.
|
AggregationOutput |
aggregate(DBObject firstOp,
DBObject... additionalOps)
Deprecated.
Use
aggregate(List, AggregationOptions) instead |
AggregationOutput |
aggregate(java.util.List<? extends DBObject> pipeline)
Deprecated.
Use
aggregate(List, AggregationOptions) instead |
Cursor |
aggregate(java.util.List<? extends DBObject> pipeline,
AggregationOptions options)
Method implements aggregation framework.
|
Cursor |
aggregate(java.util.List<? extends DBObject> pipeline,
AggregationOptions options,
ReadPreference readPreference)
Method implements aggregation framework.
|
AggregationOutput |
aggregate(java.util.List<? extends DBObject> pipeline,
ReadPreference readPreference)
Deprecated.
Use
aggregate(List, AggregationOptions, ReadPreference) )} instead |
long |
count()
Same as
getCount() |
long |
count(DBObject query)
Same as
getCount(DBObject) |
long |
count(DBObject query,
DBCollectionCountOptions options)
Get the count of documents in collection that would match a criteria.
|
long |
count(DBObject query,
ReadPreference readPreference)
Get the count of documents in collection that would match a criteria.
|
void |
createIndex(DBObject keys)
Creates an index on the field specified, if that index does not already exist.
|
void |
createIndex(DBObject keys,
DBObject options)
Creates an index on the field specified, if that index does not already exist.
|
void |
createIndex(DBObject keys,
java.lang.String name)
Forces creation of an index on a set of fields, if one does not already exist.
|
void |
createIndex(DBObject keys,
java.lang.String name,
boolean unique)
Forces creation of an index on a set of fields, if one does not already exist.
|
void |
createIndex(java.lang.String name)
Forces creation of an ascending index on a field with the default options.
|
java.util.List |
distinct(java.lang.String fieldName)
Find the distinct values for a specified field across a collection and returns the results in an array.
|
java.util.List |
distinct(java.lang.String fieldName,
DBCollectionDistinctOptions options)
Find the distinct values for a specified field across a collection and returns the results in an array.
|
java.util.List |
distinct(java.lang.String fieldName,
DBObject query)
Find the distinct values for a specified field across a collection and returns the results in an array.
|
java.util.List |
distinct(java.lang.String fieldName,
DBObject query,
ReadPreference readPreference)
Find the distinct values for a specified field across a collection and returns the results in an array.
|
java.util.List |
distinct(java.lang.String fieldName,
ReadPreference readPreference)
Find the distinct values for a specified field across a collection and returns the results in an array.
|
void |
drop()
Drops (deletes) this collection from the database.
|
void |
dropIndex(DBObject index)
Drops an index from this collection.
|
void |
dropIndex(java.lang.String indexName)
Drops the index with the given name from this collection.
|
void |
dropIndexes()
Drop all indexes on this collection.
|
void |
dropIndexes(java.lang.String indexName)
Drops the index with the given name from this collection.
|
CommandResult |
explainAggregate(java.util.List<? extends DBObject> pipeline,
AggregationOptions options)
Return the explain plan for the aggregation pipeline.
|
DBCursor |
find()
Select all documents in collection and get a cursor to the selected documents.
|
DBCursor |
find(DBObject query)
Select documents in collection and get a cursor to the selected documents.
|
DBCursor |
find(DBObject query,
DBCollectionFindOptions options)
Select documents in collection and get a cursor to the selected documents.
|
DBCursor |
find(DBObject query,
DBObject projection)
Select documents in collection and get a cursor to the selected documents.
|
DBCursor |
find(DBObject query,
DBObject projection,
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 projection,
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,
DBCollectionFindAndModifyOptions options)
Atomically modify and return a single document.
|
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,
boolean bypassDocumentValidation,
long maxTime,
java.util.concurrent.TimeUnit maxTimeUnit)
Atomically modify and return a single document.
|
DBObject |
findAndModify(DBObject query,
DBObject fields,
DBObject sort,
boolean remove,
DBObject update,
boolean returnNew,
boolean upsert,
boolean bypassDocumentValidation,
long maxTime,
java.util.concurrent.TimeUnit maxTimeUnit,
WriteConcern writeConcern)
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,
java.util.concurrent.TimeUnit maxTimeUnit)
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,
java.util.concurrent.TimeUnit maxTimeUnit,
WriteConcern writeConcern)
Atomically modify and return a single document.
|
DBObject |
findAndModify(DBObject query,
DBObject fields,
DBObject sort,
boolean remove,
DBObject update,
boolean returnNew,
boolean upsert,
WriteConcern writeConcern)
Atomically modify and return a single document.
|
DBObject |
findAndRemove(DBObject query)
Atomically remove and return a single document.
|
DBObject |
findOne()
Get a single document from collection.
|
DBObject |
findOne(DBObject query)
Get a single document from collection.
|
DBObject |
findOne(DBObject query,
DBCollectionFindOptions findOptions)
Get a single document from collection.
|
DBObject |
findOne(DBObject query,
DBObject projection)
Get a single document from collection.
|
DBObject |
findOne(DBObject query,
DBObject projection,
DBObject sort)
Get a single document from collection.
|
DBObject |
findOne(DBObject query,
DBObject projection,
DBObject sort,
ReadPreference readPreference)
Get a single document from collection.
|
DBObject |
findOne(DBObject query,
DBObject projection,
ReadPreference readPreference)
Get a single document from collection.
|
DBObject |
findOne(java.lang.Object id)
Get a single document from collection by '_id'.
|
DBObject |
findOne(java.lang.Object id,
DBObject projection)
Get a single document from collection by '_id'.
|
DBCollection |
getCollection(java.lang.String name)
Find a collection that is prefixed with this collection's name.
|
long |
getCount()
Get the count of documents in collection.
|
long |
getCount(DBObject query)
Get the count of documents in collection that would match a criteria.
|
long |
getCount(DBObject query,
DBCollectionCountOptions options)
Get the count of documents in collection that would match a criteria.
|
long |
getCount(DBObject query,
DBObject projection)
Get the count of documents in collection that would match a criteria.
|
long |
getCount(DBObject query,
DBObject projection,
long limit,
long skip)
Get the count of documents in collection that would match a criteria.
|
long |
getCount(DBObject query,
DBObject projection,
long limit,
long skip,
ReadPreference readPreference)
Get the count of documents in collection that would match a criteria.
|
long |
getCount(DBObject query,
DBObject projection,
ReadPreference readPreference)
Get the count of documents in collection that would match a criteria.
|
long |
getCount(ReadPreference readPreference)
Get the count of documents in 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.
|
java.lang.String |
getFullName()
Get the full name of a collection, with the database name as a prefix.
|
java.util.List<DBObject> |
getHintFields()
Get hint fields for this collection (used to optimize queries).
|
java.util.List<DBObject> |
getIndexInfo()
Return a list of the indexes for this collection.
|
java.lang.String |
getName()
Get the name of a collection.
|
java.lang.Class |
getObjectClass()
Gets the default class for objects in the collection
|
int |
getOptions()
Gets the default query options
|
ReadConcern |
getReadConcern()
Get the read concern for this collection.
|
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 key,
DBObject cond,
DBObject initial,
java.lang.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,
java.lang.String reduce,
java.lang.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,
java.lang.String reduce,
java.lang.String finalize,
ReadPreference readPreference)
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 readPreference)
Group documents in a collection by the specified key and performs simple aggregation functions such as computing counts and sums.
|
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... documents)
Insert documents into a collection.
|
WriteResult |
insert(DBObject[] documents,
WriteConcern writeConcern)
Insert documents into a collection.
|
WriteResult |
insert(DBObject[] documents,
WriteConcern aWriteConcern,
DBEncoder encoder)
Insert documents into a collection.
|
WriteResult |
insert(DBObject document,
WriteConcern writeConcern)
Insert a document into a collection.
|
WriteResult |
insert(java.util.List<? extends DBObject> documents)
Insert documents into a collection.
|
WriteResult |
insert(java.util.List<? extends DBObject> documents,
InsertOptions insertOptions)
Insert documents into a collection.
|
WriteResult |
insert(java.util.List<? extends DBObject> documents,
WriteConcern aWriteConcern)
Insert documents into a collection.
|
WriteResult |
insert(java.util.List<? extends DBObject> documents,
WriteConcern aWriteConcern,
DBEncoder dbEncoder)
Insert documents into a collection.
|
WriteResult |
insert(WriteConcern writeConcern,
DBObject... documents)
Insert documents into a collection.
|
boolean |
isCapped()
Checks whether this collection is capped
|
MapReduceOutput |
mapReduce(MapReduceCommand command)
Allows you to run map-reduce aggregation operations over a collection.
|
MapReduceOutput |
mapReduce(java.lang.String map,
java.lang.String reduce,
java.lang.String outputTarget,
DBObject query)
Allows you to run map-reduce aggregation operations over a collection.
|
MapReduceOutput |
mapReduce(java.lang.String map,
java.lang.String reduce,
java.lang.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(java.lang.String map,
java.lang.String reduce,
java.lang.String outputTarget,
MapReduceCommand.OutputType outputType,
DBObject query,
ReadPreference readPreference)
Allows you to run map-reduce aggregation operations over a collection and saves to a named collection.
|
java.util.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 query)
Remove documents from a collection.
|
WriteResult |
remove(DBObject query,
DBCollectionRemoveOptions options)
Remove documents from a collection.
|
WriteResult |
remove(DBObject query,
WriteConcern writeConcern)
Remove documents from a collection.
|
WriteResult |
remove(DBObject query,
WriteConcern writeConcern,
DBEncoder encoder)
Remove documents from a collection.
|
DBCollection |
rename(java.lang.String newName)
Change the name of an existing collection.
|
DBCollection |
rename(java.lang.String newName,
boolean dropTarget)
Change the name of an existing collection.
|
void |
resetOptions()
Resets the default query options
|
WriteResult |
save(DBObject document)
Update an existing document or insert a document depending on the parameter.
|
WriteResult |
save(DBObject document,
WriteConcern writeConcern)
Update an existing document or insert a document depending on the parameter.
|
void |
setDBDecoderFactory(DBDecoderFactory factory)
Set a custom decoder factory for this collection.
|
void |
setDBEncoderFactory(DBEncoderFactory factory)
Set a custom encoder factory for this collection.
|
void |
setHintFields(java.util.List<? extends DBObject> indexes)
Override MongoDB's default index selection and query optimization process.
|
void |
setInternalClass(java.lang.String path,
java.lang.Class<? extends DBObject> aClass)
Sets the internal class for the given path in the document hierarchy
|
void |
setObjectClass(java.lang.Class<? extends DBObject> aClass)
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 |
setReadConcern(ReadConcern readConcern)
Sets the read concern for this collection.
|
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() |
java.lang.String |
toString() |
WriteResult |
update(DBObject query,
DBObject update)
Modify an existing document.
|
WriteResult |
update(DBObject query,
DBObject update,
boolean upsert,
boolean multi)
Modify an existing document or documents in collection.
|
WriteResult |
update(DBObject query,
DBObject update,
boolean upsert,
boolean multi,
WriteConcern aWriteConcern)
Modify an existing document or documents in collection.
|
WriteResult |
update(DBObject query,
DBObject update,
boolean upsert,
boolean multi,
WriteConcern concern,
java.lang.Boolean bypassDocumentValidation,
DBEncoder encoder)
Modify an existing document or documents in collection.
|
WriteResult |
update(DBObject query,
DBObject update,
boolean upsert,
boolean multi,
WriteConcern concern,
DBEncoder encoder)
Modify an existing document or documents in collection.
|
WriteResult |
update(DBObject query,
DBObject update,
DBCollectionUpdateOptions options)
Modify an existing document or documents in collection.
|
WriteResult |
updateMulti(DBObject query,
DBObject update)
Modify documents in collection.
|
public static final java.lang.String ID_FIELD_NAME
public WriteResult insert(DBObject document, WriteConcern writeConcern)
document
- DBObject
to be insertedwriteConcern
- WriteConcern
to be used during operationDuplicateKeyException
- if the write failed to a duplicate unique keyWriteConcernException
- if the write failed due some other failure specific to the insert commandMongoException
- if the operation failed for some other reasonpublic WriteResult insert(DBObject... documents)
WriteConcern
will be used.documents
- DBObject
's to be insertedDuplicateKeyException
- if the write failed to a duplicate unique keyWriteConcernException
- if the write failed due some other failure specific to the insert commandMongoException
- if the operation failed for some other reasonpublic WriteResult insert(WriteConcern writeConcern, DBObject... documents)
documents
- DBObject
's to be insertedwriteConcern
- WriteConcern
to be used during operationDuplicateKeyException
- if the write failed to a duplicate unique keyWriteConcernException
- if the write failed due some other failure specific to the insert commandMongoException
- if the operation failed for some other reasonpublic WriteResult insert(DBObject[] documents, WriteConcern writeConcern)
documents
- DBObject
's to be insertedwriteConcern
- WriteConcern
to be used during operationDuplicateKeyException
- if the write failed to a duplicate unique keyWriteConcernException
- if the write failed due some other failure specific to the insert commandMongoException
- if the operation failed for some other reasonpublic WriteResult insert(java.util.List<? extends DBObject> documents)
documents
- list of DBObject
to be insertedDuplicateKeyException
- if the write failed to a duplicate unique keyWriteConcernException
- if the write failed due some other failure specific to the insert commandMongoException
- if the operation failed for some other reasonpublic WriteResult insert(java.util.List<? extends DBObject> documents, WriteConcern aWriteConcern)
documents
- list of DBObject
's to be insertedaWriteConcern
- WriteConcern
to be used during operationDuplicateKeyException
- if the write failed to a duplicate unique keyWriteConcernException
- if the write failed due some other failure specific to the insert commandMongoException
- if the operation failed for some other reasonpublic WriteResult insert(DBObject[] documents, WriteConcern aWriteConcern, DBEncoder encoder)
documents
- DBObject
's to be insertedaWriteConcern
- WriteConcern
to be used during operationencoder
- DBEncoder
to be usedDuplicateKeyException
- if the write failed to a duplicate unique keyWriteConcernException
- if the write failed due some other failure specific to the insert commandMongoException
- if the operation failed for some other reasonpublic WriteResult insert(java.util.List<? extends DBObject> documents, WriteConcern aWriteConcern, @Nullable DBEncoder dbEncoder)
documents
- a list of DBObject
's to be insertedaWriteConcern
- WriteConcern
to be used during operationdbEncoder
- DBEncoder
to be usedDuplicateKeyException
- if the write failed to a duplicate unique keyWriteConcernException
- if the write failed due some other failure specific to the insert commandMongoException
- if the operation failed for some other reasonpublic WriteResult insert(java.util.List<? extends 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 insertDuplicateKeyException
- if the write failed to a duplicate unique keyWriteConcernException
- if the write failed due some other failure specific to the insert commandMongoException
- if the operation failed for some other reasonpublic WriteResult save(DBObject document)
document
- DBObject
to save to the collection.DuplicateKeyException
- if the write failed to a duplicate unique keyWriteConcernException
- if the write failed due some other failure specific to the insert or update commandMongoException
- if the operation failed for some other reasonpublic WriteResult save(DBObject document, WriteConcern writeConcern)
document
- DBObject
to save to the collection.writeConcern
- WriteConcern
to be used during operationDuplicateKeyException
- if the write failed to a duplicate unique keyWriteConcernException
- if the write failed due some other failure specific to the insert or update commandMongoException
- if the operation failed for some other reasonpublic WriteResult update(DBObject query, DBObject update, boolean upsert, boolean multi, WriteConcern aWriteConcern)
find()
.query
- the selection criteria for the updateupdate
- 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
oneaWriteConcern
- WriteConcern
to be used during operationDuplicateKeyException
- if the write failed to a duplicate unique keyWriteConcernException
- if the write failed due some other failure specific to the update commandMongoException
- if the operation failed for some other reasonpublic WriteResult update(DBObject query, DBObject update, boolean upsert, boolean multi, WriteConcern concern, @Nullable DBEncoder encoder)
find()
.query
- the selection criteria for the updateupdate
- 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
- DBEncoder
to be usedDuplicateKeyException
- if the write failed to a duplicate unique keyWriteConcernException
- if the write failed due some other failure specific to the update commandMongoException
- if the operation failed for some other reasonpublic WriteResult update(DBObject query, DBObject update, boolean upsert, boolean multi, WriteConcern concern, @Nullable java.lang.Boolean bypassDocumentValidation, @Nullable DBEncoder encoder)
find(DBObject)
.query
- the selection criteria for the updateupdate
- 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 operationbypassDocumentValidation
- whether to bypass document validation.encoder
- the DBEncoder to useDuplicateKeyException
- if the write failed to a duplicate unique keyWriteConcernException
- if the write failed due some other failure specific to the update commandMongoException
- if the operation failed for some other reasonpublic WriteResult update(DBObject query, DBObject update, boolean upsert, boolean multi)
find()
.query
- the selection criteria for the updateupdate
- 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 oneDuplicateKeyException
- if the write failed to a duplicate unique keyWriteConcernException
- if the write failed due some other failure specific to the update commandMongoException
- if the operation failed for some other reasonpublic WriteResult update(DBObject query, DBObject update)
find()
.query
- the selection criteria for the updateupdate
- the modifications to applyDuplicateKeyException
- if the write failed to a duplicate unique keyWriteConcernException
- if the write failed due some other failure specific to the update commandMongoException
- if the operation failed for some other reasonpublic WriteResult updateMulti(DBObject query, DBObject update)
find()
.query
- the selection criteria for the updateupdate
- the modifications to applyDuplicateKeyException
- if the write failed to a duplicate unique keyWriteConcernException
- if the write failed due some other failure specific to the update commandMongoException
- if the operation failed for some other reasonpublic WriteResult update(DBObject query, DBObject update, DBCollectionUpdateOptions options)
query
- the selection criteria for the updateupdate
- the modifications to applyoptions
- the options to apply to the update operationDuplicateKeyException
- if the write failed to a duplicate unique keyWriteConcernException
- if the write failed due some other failure specific to the update commandMongoException
- if the operation failed for some other reasonpublic WriteResult remove(DBObject query)
query
- the deletion criteria using query operators. Omit the query parameter or pass an empty document to delete all documents
in the collection.WriteConcernException
- if the write failed due some other failure specific to the delete commandMongoException
- if the operation failed for some other reasonpublic WriteResult remove(DBObject query, WriteConcern writeConcern)
query
- the deletion criteria using query operators. Omit the query parameter or pass an empty document to delete all
documents in the collection.writeConcern
- WriteConcern
to be used during operationWriteConcernException
- if the write failed due some other failure specific to the delete commandMongoException
- if the operation failed for some other reasonpublic WriteResult remove(DBObject query, WriteConcern writeConcern, DBEncoder encoder)
query
- the deletion criteria using query operators. Omit the query parameter or pass an empty document to delete all
documents in the collection.writeConcern
- WriteConcern
to be used during operationencoder
- DBEncoder
to be usedWriteConcernException
- if the write failed due some other failure specific to the delete commandMongoException
- if the operation failed for some other reasonpublic WriteResult remove(DBObject query, DBCollectionRemoveOptions options)
query
- the deletion criteria using query operators. Omit the query parameter or pass an empty document to delete all
documents in the collection.options
- the options to apply to the delete operationWriteConcernException
- if the write failed due some other failure specific to the delete commandMongoException
- if the operation failed for some other reason@Deprecated public DBCursor find(DBObject query, DBObject projection, int numToSkip, int batchSize, int options)
DBCursor.skip(int)
, DBCursor.batchSize(int)
and DBCursor.setOptions(int)
on the DBCursor
returned from find(DBObject,
DBObject)
query
- the selection criteria using query operators. Omit the query parameter or pass an empty document to return all
documents in the collection.projection
- specifies which fields MongoDB will return from the documents in the result set.numToSkip
- number of documents to skipbatchSize
- see DBCursor.batchSize(int)
for more informationoptions
- query options to be used@Deprecated public DBCursor find(DBObject query, DBObject projection, int numToSkip, int batchSize)
DBCursor.skip(int)
and DBCursor.batchSize(int)
on the DBCursor
returned from find(DBObject, DBObject)
query
- the selection criteria using query operators. Omit the query parameter or pass an empty document to return all
documents in the collection.projection
- specifies which fields MongoDB will return from the documents in the result set.numToSkip
- number of documents to skipbatchSize
- see DBCursor.batchSize(int)
for more informationpublic DBCursor find(DBObject query)
query
- the selection criteria using query operators. Omit the query parameter or pass an empty document to return all documents
in the collection.public DBCursor find(DBObject query, DBObject projection)
query
- the selection criteria using query operators. Omit the query parameter or pass an empty document to return all
documents in the collection.projection
- specifies which fields MongoDB will return from the documents in the result set.public DBCursor find()
public DBCursor find(@Nullable DBObject query, DBCollectionFindOptions options)
query
- the selection criteria using query operators. Omit the query parameter or pass an empty document to return all
documents in the collection.options
- the options for the find operation.@Nullable public DBObject findOne()
@Nullable public DBObject findOne(DBObject query)
query
- the selection criteria using query operators.@Nullable public DBObject findOne(DBObject query, DBObject projection)
query
- the selection criteria using query operators.projection
- specifies which fields MongoDB will return from the documents in the result set.@Nullable public DBObject findOne(DBObject query, DBObject projection, DBObject sort)
query
- the selection criteria using query operators.projection
- specifies which fields MongoDB will return from the documents in the result set.sort
- A document whose fields specify the attributes on which to sort the result set.@Nullable public DBObject findOne(DBObject query, DBObject projection, ReadPreference readPreference)
query
- the selection criteria using query operators.projection
- specifies which fields MongoDB will return from the documents in the result set.readPreference
- ReadPreference
to be used for this operation@Nullable public DBObject findOne(@Nullable DBObject query, @Nullable DBObject projection, @Nullable DBObject sort, ReadPreference readPreference)
query
- the selection criteria using query operators.projection
- specifies which projection MongoDB will return from the documents in the result set.sort
- A document whose fields specify the attributes on which to sort the result set.readPreference
- ReadPreference
to be used for this operation@Nullable public DBObject findOne(java.lang.Object id)
id
- value of '_id' field of a document we are looking for@Nullable public DBObject findOne(java.lang.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.@Nullable public DBObject findOne(@Nullable DBObject query, DBCollectionFindOptions findOptions)
query
- the selection criteria using query operators.findOptions
- the options for the find operation.public long count()
getCount()
MongoException
- if the operation failedpublic long count(@Nullable DBObject query)
getCount(DBObject)
query
- specifies the selection criteriaMongoException
- if the operation failedpublic long count(@Nullable DBObject query, ReadPreference readPreference)
query
- specifies the selection criteriareadPreference
- ReadPreference
to be used for this operationMongoException
- if the operation failedpublic long count(@Nullable DBObject query, DBCollectionCountOptions options)
query
- specifies the selection criteriaoptions
- the options for the count operation.MongoException
- if the operation failedpublic long getCount()
MongoException
- if the operation failedpublic long getCount(ReadPreference readPreference)
readPreference
- ReadPreference
to be used for this operationMongoException
- if the operation failedpublic long getCount(@Nullable DBObject query)
query
- specifies the selection criteriaMongoException
- if the operation failedpublic long getCount(@Nullable DBObject query, DBObject projection)
query
- specifies the selection criteriaprojection
- this is ignoredMongoException
- if the operation failedpublic long getCount(@Nullable DBObject query, @Nullable DBObject projection, ReadPreference readPreference)
query
- specifies the selection criteriaprojection
- this is ignoredreadPreference
- ReadPreference
to be used for this operationMongoException
- if the operation failedpublic long getCount(@Nullable DBObject query, @Nullable DBObject projection, long limit, long skip)
query
- specifies the selection criteriaprojection
- this is ignoredlimit
- limit the count to this valueskip
- number of documents to skipMongoException
- if the operation failedpublic long getCount(@Nullable DBObject query, @Nullable DBObject projection, long limit, long skip, ReadPreference readPreference)
query
- specifies the selection criteriaprojection
- this is ignoredlimit
- limit the count to this valueskip
- number of documents to skipreadPreference
- ReadPreference
to be used for this operationMongoException
- if the operation failedpublic long getCount(@Nullable DBObject query, DBCollectionCountOptions options)
query
- specifies the selection criteriaoptions
- the options for the count operation.MongoException
- if the operation failedpublic DBCollection rename(java.lang.String newName)
newName
- specifies the new name of the collectionMongoException
- if newName is the name of an existing collection.public DBCollection rename(java.lang.String newName, boolean dropTarget)
newName
- specifies the new name of the collectiondropTarget
- If true
, mongod will drop the collection with the target name if it existsMongoException
- if target is the name of an existing collection and dropTarget=false
.public DBObject group(DBObject key, DBObject cond, DBObject initial, java.lang.String reduce)
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 function, that operates on the documents during the grouping operationpublic DBObject group(DBObject key, DBObject cond, DBObject initial, java.lang.String reduce, @Nullable java.lang.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 returnedpublic DBObject group(DBObject key, DBObject cond, DBObject initial, java.lang.String reduce, @Nullable java.lang.String finalize, ReadPreference readPreference)
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 returnedreadPreference
- ReadPreference
to be used for this operationpublic DBObject group(GroupCommand cmd)
SELECT ... GROUP BY
statement in SQL.cmd
- the group commandpublic DBObject group(GroupCommand cmd, ReadPreference readPreference)
SELECT ... GROUP BY
statement in SQL.cmd
- the group commandreadPreference
- ReadPreference
to be used for this operationpublic java.util.List distinct(java.lang.String fieldName)
fieldName
- Specifies the field for which to return the distinct values.public java.util.List distinct(java.lang.String fieldName, ReadPreference readPreference)
fieldName
- Specifies the field for which to return the distinct valuesreadPreference
- ReadPreference
to be used for this operationpublic java.util.List distinct(java.lang.String fieldName, DBObject query)
fieldName
- 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 valuespublic java.util.List distinct(java.lang.String fieldName, DBObject query, ReadPreference readPreference)
fieldName
- 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 valuesreadPreference
- ReadPreference
to be used for this operationList
of the distinct valuespublic java.util.List distinct(java.lang.String fieldName, DBCollectionDistinctOptions options)
fieldName
- Specifies the field for which to return the distinct valuesoptions
- the options to apply for this operationList
of the distinct valuespublic MapReduceOutput mapReduce(java.lang.String map, java.lang.String reduce, java.lang.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.query
- specifies the selection criteria using query operators for determining the documents input to the map function.public MapReduceOutput mapReduce(java.lang.String map, java.lang.String reduce, java.lang.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.outputType
- specifies the type of job outputquery
- specifies the selection criteria using query operators for determining the documents input to the map function.public MapReduceOutput mapReduce(java.lang.String map, java.lang.String reduce, java.lang.String outputTarget, MapReduceCommand.OutputType outputType, DBObject query, ReadPreference readPreference)
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.outputType
- specifies the type of job outputquery
- specifies the selection criteria using query operators for determining the documents input to the map
function.readPreference
- the read preference specifying where to run the query. Only applied for Inline output typepublic MapReduceOutput mapReduce(MapReduceCommand command)
command
- specifies the details of the Map Reduce operation to perform@Deprecated public AggregationOutput aggregate(DBObject firstOp, DBObject... additionalOps)
aggregate(List, AggregationOptions)
insteadfirstOp
- requisite first operation to be performed in the aggregation pipelineadditionalOps
- additional operations to be performed in the aggregation pipeline@Deprecated public AggregationOutput aggregate(java.util.List<? extends DBObject> pipeline)
aggregate(List, AggregationOptions)
insteadpipeline
- operations to be performed in the aggregation pipeline@Deprecated public AggregationOutput aggregate(java.util.List<? extends DBObject> pipeline, ReadPreference readPreference)
aggregate(List, AggregationOptions, ReadPreference)
)} insteadpipeline
- operations to be performed in the aggregation pipelinereadPreference
- the read preference specifying where to run the querypublic Cursor aggregate(java.util.List<? extends DBObject> pipeline, AggregationOptions options)
pipeline
- operations to be performed in the aggregation pipelineoptions
- options to apply to the aggregationpublic Cursor aggregate(java.util.List<? extends 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(java.util.List<? extends DBObject> pipeline, AggregationOptions options)
pipeline
- the aggregation pipeline to explainoptions
- the options to apply to the aggregationpublic java.util.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 java.lang.String getName()
public java.lang.String getFullName()
public DBCollection getCollection(java.lang.String name)
DBCollection users = mongo.getCollection( "wiki" ).getCollection( "users" );
Which is equivalent to
DBCollection users = mongo.getCollection( "wiki.users" );
name
- the name of the collection to findpublic void createIndex(java.lang.String name)
name
- name of field to index onMongoException
- if the operation failedpublic void createIndex(DBObject keys, java.lang.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
- if the operation failedpublic void createIndex(DBObject keys, @Nullable java.lang.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
- if the operation failedpublic void createIndex(DBObject keys)
keys
- a document that contains pairs with the name of the field or fields to index and order of the indexpublic void createIndex(DBObject keys, DBObject options)
Prior to MongoDB 3.0 the dropDups option could be used with unique indexes allowing documents with duplicate values to be dropped when building the index. Later versions of MongoDB will silently ignore this setting.
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.@Nullable public java.util.List<DBObject> getHintFields()
DBObject
to be used as hints.public void setHintFields(java.util.List<? extends DBObject> indexes)
indexes
- list of indexes to "hint" or force MongoDB to use when performing the query.@Nullable public DBObject findAndModify(@Nullable DBObject query, @Nullable DBObject sort, DBObject update)
query
- specifies the selection criteria for the modificationsort
- determines which document the operation will modify if the query selects multiple documentsupdate
- the modifications to applyWriteConcernException
- if the write failed due some other failure specific to the update commandMongoException
- if the operation failed for some other reason@Nullable public DBObject findAndModify(@Nullable DBObject query, DBObject update)
query
- specifies the selection criteria for the modificationupdate
- the modifications to applyWriteConcernException
- if the write failed due some other failure specific to the update commandMongoException
- if the operation failed for some other reason@Nullable public DBObject findAndRemove(@Nullable DBObject query)
query
- specifies the selection criteria for the modificationWriteConcernException
- if the write failed due some other failure specific to the update commandMongoException
- if the operation failed for some other reason@Nullable public DBObject findAndModify(@Nullable DBObject query, @Nullable DBObject fields, @Nullable DBObject sort, boolean remove, @Nullable 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 madeWriteConcernException
- if the write failed due some other failure specific to the update commandMongoException
- if the operation failed for some other reason@Nullable public DBObject findAndModify(@Nullable DBObject query, @Nullable DBObject fields, @Nullable DBObject sort, boolean remove, DBObject update, boolean returnNew, boolean upsert, WriteConcern writeConcern)
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 documentswriteConcern
- the write concern to apply to this operationreturnNew
is true, in which case it returns the document
after the changes were madeWriteConcernException
- if the write failed due some other failure specific to the update commandMongoException
- if the operation failed for some other reason@Nullable public DBObject findAndModify(@Nullable DBObject query, @Nullable DBObject fields, @Nullable DBObject sort, boolean remove, @Nullable DBObject update, boolean returnNew, boolean upsert, long maxTime, java.util.concurrent.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
- the modifications to applyupsert
- 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 madeWriteConcernException
- if the write failed due some other failure specific to the update commandMongoException
- if the operation failed for some other reason@Nullable public DBObject findAndModify(@Nullable DBObject query, @Nullable DBObject fields, @Nullable DBObject sort, boolean remove, @Nullable DBObject update, boolean returnNew, boolean upsert, long maxTime, java.util.concurrent.TimeUnit maxTimeUnit, WriteConcern writeConcern)
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 inwriteConcern
- the write concern to apply to this operationreturnNew
is true, in which case it returns the document
after the changes were madeWriteConcernException
- if the write failed due some other failure specific to the update commandMongoException
- if the operation failed for some other reason@Nullable public DBObject findAndModify(DBObject query, DBObject fields, DBObject sort, boolean remove, @Nullable DBObject update, boolean returnNew, boolean upsert, boolean bypassDocumentValidation, long maxTime, java.util.concurrent.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 documentsbypassDocumentValidation
- whether to bypass document validation.maxTime
- 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 madeWriteConcernException
- if the write failed due some other failure specific to the update commandMongoException
- if the operation failed for some other reasonpublic DBObject findAndModify(@Nullable DBObject query, @Nullable DBObject fields, @Nullable DBObject sort, boolean remove, @Nullable DBObject update, boolean returnNew, boolean upsert, boolean bypassDocumentValidation, long maxTime, java.util.concurrent.TimeUnit maxTimeUnit, WriteConcern writeConcern)
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 documentsbypassDocumentValidation
- whether to bypass document validation.maxTime
- 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 inwriteConcern
- the write concern to apply to this operationreturnNew
is true, in which case it returns the document
after the changes were madeWriteConcernException
- if the write failed due some other failure specific to the update commandMongoException
- if the operation failed for some other reasonpublic DBObject findAndModify(DBObject query, DBCollectionFindAndModifyOptions options)
query
- specifies the selection criteria for the modificationoptions
- the options regarding the find and modify operationoprtions.returnNew
is true, in which case it returns the
document after the changes were madeWriteConcernException
- if the write failed due some other failure specific to the update commandMongoException
- if the operation failed for some other reasonpublic DB getDB()
public WriteConcern getWriteConcern()
WriteConcern
for this collection.public 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 ReadPreference getReadPreference()
ReadPreference
.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 void setReadConcern(ReadConcern readConcern)
readConcern
- the read concern to use for this collectionpublic ReadConcern getReadConcern()
ReadConcern
@Deprecated public void slaveOk()
ReadPreference.secondaryPreferred()
public void addOption(int option)
option
- value to be addedpublic void resetOptions()
public int getOptions()
public void setOptions(int options)
options
- bit vector of query optionspublic void drop()
MongoException
- if the operation failedpublic DBDecoderFactory getDBDecoderFactory()
public void setDBDecoderFactory(@Nullable DBDecoderFactory factory)
factory
- the factory to set.public DBEncoderFactory getDBEncoderFactory()
public void setDBEncoderFactory(@Nullable DBEncoderFactory factory)
factory
- the factory to set.public java.util.List<DBObject> getIndexInfo()
MongoException
- if the operation failedpublic void dropIndex(DBObject index)
index
- the specification of the index to dropMongoException
- if the index does not existpublic void dropIndex(java.lang.String indexName)
indexName
- name of index to dropMongoException
- if the index does not existpublic void dropIndexes()
public void dropIndexes(java.lang.String indexName)
dropIndex(indexName)
.indexName
- name of index to dropMongoException
- if the index does not existpublic CommandResult getStats()
public boolean isCapped()
public java.lang.Class getObjectClass()
public void setObjectClass(java.lang.Class<? extends DBObject> aClass)
aClass
- the classpublic void setInternalClass(java.lang.String path, java.lang.Class<? extends DBObject> aClass)
path
- the path to map the given Class toaClass
- the Class to map the given path topublic java.lang.String toString()
toString
in class java.lang.Object
public 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.
Copyright © 2010 - 2020 Adobe. All Rights Reserved