All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.mongodb.MongoCollectionImpl Maven / Gradle / Ivy

Go to download

The MongoDB Java Driver uber-artifact, containing mongodb-driver, mongodb-driver-core, and bson

The newest version!
/*
 * Copyright (c) 2008-2015 MongoDB, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mongodb;

import com.mongodb.bulk.BulkWriteResult;
import com.mongodb.bulk.DeleteRequest;
import com.mongodb.bulk.IndexRequest;
import com.mongodb.bulk.InsertRequest;
import com.mongodb.bulk.UpdateRequest;
import com.mongodb.bulk.WriteRequest;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.DistinctIterable;
import com.mongodb.client.FindIterable;
import com.mongodb.client.ListIndexesIterable;
import com.mongodb.client.MapReduceIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.BulkWriteOptions;
import com.mongodb.client.model.CountOptions;
import com.mongodb.client.model.DeleteManyModel;
import com.mongodb.client.model.DeleteOneModel;
import com.mongodb.client.model.FindOneAndDeleteOptions;
import com.mongodb.client.model.FindOneAndReplaceOptions;
import com.mongodb.client.model.FindOneAndUpdateOptions;
import com.mongodb.client.model.FindOptions;
import com.mongodb.client.model.IndexModel;
import com.mongodb.client.model.IndexOptions;
import com.mongodb.client.model.InsertManyOptions;
import com.mongodb.client.model.InsertOneModel;
import com.mongodb.client.model.RenameCollectionOptions;
import com.mongodb.client.model.ReplaceOneModel;
import com.mongodb.client.model.ReturnDocument;
import com.mongodb.client.model.UpdateManyModel;
import com.mongodb.client.model.UpdateOneModel;
import com.mongodb.client.model.UpdateOptions;
import com.mongodb.client.model.WriteModel;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.mongodb.operation.CountOperation;
import com.mongodb.operation.CreateIndexesOperation;
import com.mongodb.operation.DropCollectionOperation;
import com.mongodb.operation.DropIndexOperation;
import com.mongodb.operation.FindAndDeleteOperation;
import com.mongodb.operation.FindAndReplaceOperation;
import com.mongodb.operation.FindAndUpdateOperation;
import com.mongodb.operation.MixedBulkWriteOperation;
import com.mongodb.operation.OperationExecutor;
import com.mongodb.operation.RenameCollectionOperation;
import org.bson.BsonDocument;
import org.bson.BsonDocumentWrapper;
import org.bson.BsonString;
import org.bson.BsonValue;
import org.bson.Document;
import org.bson.codecs.Codec;
import org.bson.codecs.CollectibleCodec;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.conversions.Bson;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.mongodb.assertions.Assertions.notNull;
import static java.lang.String.format;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static java.util.concurrent.TimeUnit.MILLISECONDS;

class MongoCollectionImpl implements MongoCollection {
    private final MongoNamespace namespace;
    private final Class documentClass;
    private final ReadPreference readPreference;
    private final CodecRegistry codecRegistry;
    private final WriteConcern writeConcern;
    private final OperationExecutor executor;

    MongoCollectionImpl(final MongoNamespace namespace, final Class documentClass, final CodecRegistry codecRegistry,
                        final ReadPreference readPreference, final WriteConcern writeConcern, final OperationExecutor executor) {
        this.namespace = notNull("namespace", namespace);
        this.documentClass = notNull("documentClass", documentClass);
        this.codecRegistry = notNull("codecRegistry", codecRegistry);
        this.readPreference = notNull("readPreference", readPreference);
        this.writeConcern = notNull("writeConcern", writeConcern);
        this.executor = notNull("executor", executor);
    }

    @Override
    public MongoNamespace getNamespace() {
        return namespace;
    }

    @Override
    public Class getDocumentClass() {
        return documentClass;
    }

    @Override
    public CodecRegistry getCodecRegistry() {
        return codecRegistry;
    }

    @Override
    public ReadPreference getReadPreference() {
        return readPreference;
    }

    @Override
    public WriteConcern getWriteConcern() {
        return writeConcern;
    }

    @Override
    public  MongoCollection withDocumentClass(final Class clazz) {
        return new MongoCollectionImpl(namespace, clazz, codecRegistry, readPreference, writeConcern, executor);
    }

    @Override
    public MongoCollection withCodecRegistry(final CodecRegistry codecRegistry) {
        return new MongoCollectionImpl(namespace, documentClass, codecRegistry, readPreference, writeConcern, executor);
    }

    @Override
    public MongoCollection withReadPreference(final ReadPreference readPreference) {
        return new MongoCollectionImpl(namespace, documentClass, codecRegistry, readPreference, writeConcern, executor);
    }

    @Override
    public MongoCollection withWriteConcern(final WriteConcern writeConcern) {
        return new MongoCollectionImpl(namespace, documentClass, codecRegistry, readPreference, writeConcern, executor);
    }

    @Override
    public long count() {
        return count(new BsonDocument(), new CountOptions());
    }

    @Override
    public long count(final Bson filter) {
        return count(filter, new CountOptions());
    }

    @Override
    public long count(final Bson filter, final CountOptions options) {
        CountOperation operation = new CountOperation(namespace)
                                       .filter(toBsonDocument(filter))
                                       .skip(options.getSkip())
                                       .limit(options.getLimit())
                                       .maxTime(options.getMaxTime(MILLISECONDS), MILLISECONDS);
        if (options.getHint() != null) {
            operation.hint(toBsonDocument(options.getHint()));
        } else if (options.getHintString() != null) {
            operation.hint(new BsonString(options.getHintString()));
        }
        return executor.execute(operation, readPreference);
    }

    @Override
    public  DistinctIterable distinct(final String fieldName, final Class resultClass) {
        return distinct(fieldName, new BsonDocument(), resultClass);
    }

    @Override
    public  DistinctIterable distinct(final String fieldName, final Bson filter, final Class resultClass) {
        return new DistinctIterableImpl(namespace, documentClass, resultClass, codecRegistry, readPreference, executor,
                fieldName, filter);
    }

    @Override
    public FindIterable find() {
        return find(new BsonDocument(), documentClass);
    }

    @Override
    public  FindIterable find(final Class resultClass) {
        return find(new BsonDocument(), resultClass);
    }

    @Override
    public FindIterable find(final Bson filter) {
        return find(filter, documentClass);
    }

    @Override
    public  FindIterable find(final Bson filter, final Class resultClass) {
        return new FindIterableImpl(namespace, this.documentClass, resultClass, codecRegistry, readPreference, executor,
                                                        filter, new FindOptions());
    }

    @Override
    public AggregateIterable aggregate(final List pipeline) {
        return aggregate(pipeline, documentClass);
    }

    @Override
    public  AggregateIterable aggregate(final List pipeline, final Class resultClass) {
        return new AggregateIterableImpl(namespace, documentClass, resultClass, codecRegistry, readPreference, executor,
                                                             pipeline);
    }

    @Override
    public MapReduceIterable mapReduce(final String mapFunction, final String reduceFunction) {
        return mapReduce(mapFunction, reduceFunction, documentClass);
    }

    @Override
    public  MapReduceIterable mapReduce(final String mapFunction, final String reduceFunction,
                                                          final Class resultClass) {
        return new MapReduceIterableImpl(namespace, documentClass, resultClass, codecRegistry, readPreference, executor,
                                                             mapFunction, reduceFunction);
    }

    @Override
    public BulkWriteResult bulkWrite(final List> requests) {
        return bulkWrite(requests, new BulkWriteOptions());
    }

    @Override
    @SuppressWarnings("unchecked")
    public BulkWriteResult bulkWrite(final List> requests, final BulkWriteOptions options) {
        List writeRequests = new ArrayList(requests.size());
        for (WriteModel writeModel : requests) {
            WriteRequest writeRequest;
            if (writeModel instanceof InsertOneModel) {
                TDocument document = ((InsertOneModel) writeModel).getDocument();
                if (getCodec() instanceof CollectibleCodec) {
                    document = ((CollectibleCodec) getCodec()).generateIdIfAbsentFromDocument(document);
                }
                writeRequest = new InsertRequest(documentToBsonDocument(document));
            } else if (writeModel instanceof ReplaceOneModel) {
                ReplaceOneModel replaceOneModel = (ReplaceOneModel) writeModel;
                writeRequest = new UpdateRequest(toBsonDocument(replaceOneModel.getFilter()), documentToBsonDocument(replaceOneModel
                                                                                                                     .getReplacement()),
                                                 WriteRequest.Type.REPLACE)
                                   .upsert(replaceOneModel.getOptions().isUpsert());
            } else if (writeModel instanceof UpdateOneModel) {
                UpdateOneModel updateOneModel = (UpdateOneModel) writeModel;
                writeRequest = new UpdateRequest(toBsonDocument(updateOneModel.getFilter()), toBsonDocument(updateOneModel.getUpdate()),
                                                 WriteRequest.Type.UPDATE)
                                   .multi(false)
                                   .upsert(updateOneModel.getOptions().isUpsert());
            } else if (writeModel instanceof UpdateManyModel) {
                UpdateManyModel updateManyModel = (UpdateManyModel) writeModel;
                writeRequest = new UpdateRequest(toBsonDocument(updateManyModel.getFilter()), toBsonDocument(updateManyModel.getUpdate()),
                                                 WriteRequest.Type.UPDATE)
                                   .multi(true)
                                   .upsert(updateManyModel.getOptions().isUpsert());
            } else if (writeModel instanceof DeleteOneModel) {
                DeleteOneModel deleteOneModel = (DeleteOneModel) writeModel;
                writeRequest = new DeleteRequest(toBsonDocument(deleteOneModel.getFilter())).multi(false);
            } else if (writeModel instanceof DeleteManyModel) {
                DeleteManyModel deleteManyModel = (DeleteManyModel) writeModel;
                writeRequest = new DeleteRequest(toBsonDocument(deleteManyModel.getFilter())).multi(true);
            } else {
                throw new UnsupportedOperationException(format("WriteModel of type %s is not supported", writeModel.getClass()));
            }

            writeRequests.add(writeRequest);
        }

        return executor.execute(new MixedBulkWriteOperation(namespace, writeRequests, options.isOrdered(), writeConcern));
    }

    @Override
    public void insertOne(final TDocument document) {
        TDocument insertDocument = document;
        if (getCodec() instanceof CollectibleCodec) {
            insertDocument = ((CollectibleCodec) getCodec()).generateIdIfAbsentFromDocument(document);
        }
        executeSingleWriteRequest(new InsertRequest(documentToBsonDocument(insertDocument)));
    }

    @Override
    public void insertMany(final List documents) {
        insertMany(documents, new InsertManyOptions());
    }

    @Override
    public void insertMany(final List documents, final InsertManyOptions options) {
        List requests = new ArrayList(documents.size());
        for (TDocument document : documents) {
            if (getCodec() instanceof CollectibleCodec) {
                document = ((CollectibleCodec) getCodec()).generateIdIfAbsentFromDocument(document);
            }
            requests.add(new InsertRequest(documentToBsonDocument(document)));
        }
        executor.execute(new MixedBulkWriteOperation(namespace, requests, options.isOrdered(), writeConcern));
    }

    @Override
    public DeleteResult deleteOne(final Bson filter) {
        return delete(filter, false);
    }

    @Override
    public DeleteResult deleteMany(final Bson filter) {
        return delete(filter, true);
    }

    @Override
    public UpdateResult replaceOne(final Bson filter, final TDocument replacement) {
        return replaceOne(filter, replacement, new UpdateOptions());
    }

    @Override
    public UpdateResult replaceOne(final Bson filter, final TDocument replacement, final UpdateOptions updateOptions) {
        return toUpdateResult(executeSingleWriteRequest(new UpdateRequest(toBsonDocument(filter), documentToBsonDocument(replacement),
                                                                          WriteRequest.Type.REPLACE).upsert(updateOptions.isUpsert())));
    }

    @Override
    public UpdateResult updateOne(final Bson filter, final Bson update) {
        return updateOne(filter, update, new UpdateOptions());
    }

    @Override
    public UpdateResult updateOne(final Bson filter, final Bson update, final UpdateOptions updateOptions) {
        return update(filter, update, updateOptions, false);
    }

    @Override
    public UpdateResult updateMany(final Bson filter, final Bson update) {
        return updateMany(filter, update, new UpdateOptions());
    }

    @Override
    public UpdateResult updateMany(final Bson filter, final Bson update, final UpdateOptions updateOptions) {
        return update(filter, update, updateOptions, true);
    }

    @Override
    public TDocument findOneAndDelete(final Bson filter) {
        return findOneAndDelete(filter, new FindOneAndDeleteOptions());
    }

    @Override
    public TDocument findOneAndDelete(final Bson filter, final FindOneAndDeleteOptions options) {
        return executor.execute(new FindAndDeleteOperation(namespace, getCodec())
                                .filter(toBsonDocument(filter))
                                .projection(toBsonDocument(options.getProjection()))
                                .sort(toBsonDocument(options.getSort()))
                                .maxTime(options.getMaxTime(MILLISECONDS), MILLISECONDS));
    }

    @Override
    public TDocument findOneAndReplace(final Bson filter, final TDocument replacement) {
        return findOneAndReplace(filter, replacement, new FindOneAndReplaceOptions());
    }

    @Override
    public TDocument findOneAndReplace(final Bson filter, final TDocument replacement, final FindOneAndReplaceOptions options) {
        return executor.execute(new FindAndReplaceOperation(namespace, getCodec(), documentToBsonDocument(replacement))
                                .filter(toBsonDocument(filter))
                                .projection(toBsonDocument(options.getProjection()))
                                .sort(toBsonDocument(options.getSort()))
                                .returnOriginal(options.getReturnDocument() == ReturnDocument.BEFORE)
                                .upsert(options.isUpsert())
                                .maxTime(options.getMaxTime(MILLISECONDS), MILLISECONDS));
    }

    @Override
    public TDocument findOneAndUpdate(final Bson filter, final Bson update) {
        return findOneAndUpdate(filter, update, new FindOneAndUpdateOptions());
    }

    @Override
    public TDocument findOneAndUpdate(final Bson filter, final Bson update, final FindOneAndUpdateOptions options) {
        return executor.execute(new FindAndUpdateOperation(namespace, getCodec(), toBsonDocument(update))
                                .filter(toBsonDocument(filter))
                                .projection(toBsonDocument(options.getProjection()))
                                .sort(toBsonDocument(options.getSort()))
                                .returnOriginal(options.getReturnDocument() == ReturnDocument.BEFORE)
                                .upsert(options.isUpsert())
                                .maxTime(options.getMaxTime(MILLISECONDS), MILLISECONDS));
    }

    @Override
    public void drop() {
        executor.execute(new DropCollectionOperation(namespace));
    }

    @Override
    public String createIndex(final Bson keys) {
        return createIndex(keys, new IndexOptions());
    }

    @Override
    public String createIndex(final Bson keys, final IndexOptions indexOptions) {
        return createIndexes(singletonList(new IndexModel(keys, indexOptions))).get(0);
    }

    @Override
    public List createIndexes(final List indexes) {
        notNull("indexes", indexes);

        List indexRequests = new ArrayList(indexes.size());
        for (IndexModel model : indexes) {
            indexRequests.add(new IndexRequest(toBsonDocument(model.getKeys()))
                         .name(model.getOptions().getName())
                         .background(model.getOptions().isBackground())
                         .unique(model.getOptions().isUnique())
                         .sparse(model.getOptions().isSparse())
                         .expireAfter(model.getOptions().getExpireAfter(TimeUnit.SECONDS), TimeUnit.SECONDS)
                         .version(model.getOptions().getVersion())
                         .weights(toBsonDocument(model.getOptions().getWeights()))
                         .defaultLanguage(model.getOptions().getDefaultLanguage())
                         .languageOverride(model.getOptions().getLanguageOverride())
                         .textVersion(model.getOptions().getTextVersion())
                         .sphereVersion(model.getOptions().getSphereVersion())
                         .bits(model.getOptions().getBits())
                         .min(model.getOptions().getMin())
                         .max(model.getOptions().getMax())
                         .bucketSize(model.getOptions().getBucketSize())
                         .storageEngine(toBsonDocument(model.getOptions().getStorageEngine())));
        }
        CreateIndexesOperation createIndexesOperation = new CreateIndexesOperation(getNamespace(), indexRequests);
        executor.execute(createIndexesOperation);
        return createIndexesOperation.getIndexNames();
    }

    @Override
    public ListIndexesIterable listIndexes() {
        return listIndexes(Document.class);
    }

    @Override
    public  ListIndexesIterable listIndexes(final Class resultClass) {
        return new ListIndexesIterableImpl(getNamespace(), resultClass, codecRegistry, ReadPreference.primary(), executor);
    }

    @Override
    public void dropIndex(final String indexName) {
        executor.execute(new DropIndexOperation(namespace, indexName));
    }

    @Override
    public void dropIndex(final Bson keys) {
        executor.execute(new DropIndexOperation(namespace, keys.toBsonDocument(BsonDocument.class, codecRegistry)));
    }

    @Override
    public void dropIndexes() {
        dropIndex("*");
    }

    @Override
    public void renameCollection(final MongoNamespace newCollectionNamespace) {
        renameCollection(newCollectionNamespace, new RenameCollectionOptions());
    }

    @Override
    public void renameCollection(final MongoNamespace newCollectionNamespace, final RenameCollectionOptions renameCollectionOptions) {
        executor.execute(new RenameCollectionOperation(getNamespace(), newCollectionNamespace)
                             .dropTarget(renameCollectionOptions.isDropTarget()));
    }

    private DeleteResult delete(final Bson filter, final boolean multi) {
        com.mongodb.bulk.BulkWriteResult result = executeSingleWriteRequest(new DeleteRequest(toBsonDocument(filter)).multi(multi));
        if (result.wasAcknowledged()) {
            return DeleteResult.acknowledged(result.getDeletedCount());
        } else {
            return DeleteResult.unacknowledged();
        }
    }

    private UpdateResult update(final Bson filter, final Bson update, final UpdateOptions updateOptions, final boolean multi) {
        return toUpdateResult(executeSingleWriteRequest(new UpdateRequest(toBsonDocument(filter), toBsonDocument(update),
                                                                          WriteRequest.Type.UPDATE)
                                                        .upsert(updateOptions.isUpsert()).multi(multi)));
    }


    private BulkWriteResult executeSingleWriteRequest(final WriteRequest request) {
        try {
            return executor.execute(new MixedBulkWriteOperation(namespace, asList(request), true, writeConcern));
        } catch (MongoBulkWriteException e) {
            if (e.getWriteErrors().isEmpty()) {
                throw new MongoWriteConcernException(e.getWriteConcernError(), e.getServerAddress());
            } else {
                throw new MongoWriteException(new WriteError(e.getWriteErrors().get(0)), e.getServerAddress());
            }
        }
    }

    private UpdateResult toUpdateResult(final com.mongodb.bulk.BulkWriteResult result) {
        if (result.wasAcknowledged()) {
            Long modifiedCount = result.isModifiedCountAvailable() ? (long) result.getModifiedCount() : null;
            BsonValue upsertedId = result.getUpserts().isEmpty() ? null : result.getUpserts().get(0).getId();
            return UpdateResult.acknowledged(result.getMatchedCount(), modifiedCount, upsertedId);
        } else {
            return UpdateResult.unacknowledged();
        }
    }

    private Codec getCodec() {
        return codecRegistry.get(documentClass);
    }

    private BsonDocument documentToBsonDocument(final TDocument document) {
        return BsonDocumentWrapper.asBsonDocument(document, codecRegistry);
    }

    private BsonDocument toBsonDocument(final Bson bson) {
        return bson == null ? null : bson.toBsonDocument(documentClass, codecRegistry);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy