Search in sources :

Example 1 with DistinctOperation

use of com.mongodb.operation.DistinctOperation in project mongo-java-driver by mongodb.

the class DBCollection method distinct.

/**
     * Find the distinct values for a specified field across a collection and returns the results in an array.
     *
     * @param fieldName  Specifies the field for which to return the distinct values
     * @param options    the options to apply for this operation
     * @return A {@code List} of the distinct values
     * @mongodb.driver.manual reference/command/distinct Distinct Command
     * @since 3.4
     */
@SuppressWarnings("unchecked")
public List distinct(final String fieldName, final DBCollectionDistinctOptions options) {
    notNull("fieldName", fieldName);
    return new OperationIterable<BsonValue>(new DistinctOperation<BsonValue>(getNamespace(), fieldName, new BsonValueCodec()).readConcern(options.getReadConcern() != null ? options.getReadConcern() : getReadConcern()).filter(wrapAllowNull(options.getFilter())).collation(options.getCollation()), options.getReadPreference() != null ? options.getReadPreference() : getReadPreference(), executor).map(new Function<BsonValue, Object>() {

        @Override
        public Object apply(final BsonValue bsonValue) {
            if (bsonValue == null) {
                return null;
            }
            BsonDocument document = new BsonDocument("value", bsonValue);
            DBObject obj = getDefaultDBObjectCodec().decode(new BsonDocumentReader(document), DecoderContext.builder().build());
            return obj.get("value");
        }
    }).into(new ArrayList<Object>());
}
Also used : DistinctOperation(com.mongodb.operation.DistinctOperation) BsonValueCodec(org.bson.codecs.BsonValueCodec) BsonDocument(org.bson.BsonDocument) BsonDocumentReader(org.bson.BsonDocumentReader) BsonValue(org.bson.BsonValue)

Aggregations

DistinctOperation (com.mongodb.operation.DistinctOperation)1 BsonDocument (org.bson.BsonDocument)1 BsonDocumentReader (org.bson.BsonDocumentReader)1 BsonValue (org.bson.BsonValue)1 BsonValueCodec (org.bson.codecs.BsonValueCodec)1