Search in sources :

Example 26 with DBCollection

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

the class Decimal128LegacyAPIQuickTour method main.

/**
     * Run this main method to see the output of this quick example.
     *
     * @param args takes an optional single argument for the connection string
     */
public static void main(final String[] args) {
    MongoClient mongoClient;
    if (args.length == 0) {
        // connect to the local database server
        mongoClient = new MongoClient();
    } else {
        mongoClient = new MongoClient(new MongoClientURI(args[0]));
    }
    // get handle to "mydb" database
    DB database = mongoClient.getDB("mydb");
    // get a handle to the "test" collection
    DBCollection collection = database.getCollection("test");
    // drop all the data in it
    collection.drop();
    // make a document and insert it
    BasicDBObject doc = new BasicDBObject("name", "MongoDB").append("amount1", Decimal128.parse(".10")).append("amount2", new Decimal128(42L)).append("amount3", new Decimal128(new BigDecimal(".200")));
    collection.insert(doc);
    DBObject first = collection.findOne(QueryBuilder.start("amount1").is(new Decimal128(new BigDecimal(".10"))).get());
    Decimal128 amount3 = (Decimal128) first.get("amount3");
    BigDecimal amount2AsBigDecimal = amount3.bigDecimalValue();
    System.out.println(amount3.toString());
    System.out.println(amount2AsBigDecimal.toString());
}
Also used : MongoClient(com.mongodb.MongoClient) DBCollection(com.mongodb.DBCollection) BasicDBObject(com.mongodb.BasicDBObject) MongoClientURI(com.mongodb.MongoClientURI) Decimal128(org.bson.types.Decimal128) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) DB(com.mongodb.DB) BigDecimal(java.math.BigDecimal)

Example 27 with DBCollection

use of com.mongodb.DBCollection in project morphia by mongodb.

the class DatastoreImpl method mapReduce.

@Override
@Deprecated
public <T> MapreduceResults<T> mapReduce(final MapreduceType type, final Query query, final Class<T> outputType, final MapReduceCommand baseCommand) {
    Assert.parametersNotNull("map", baseCommand.getMap());
    Assert.parameterNotEmpty("map", baseCommand.getMap());
    Assert.parametersNotNull("reduce", baseCommand.getReduce());
    Assert.parameterNotEmpty("reduce", baseCommand.getReduce());
    if (query.getOffset() != 0 || query.getFieldsObject() != null) {
        throw new QueryException("mapReduce does not allow the offset/retrievedFields query options.");
    }
    final OutputType outType = type.toOutputType();
    final DBCollection dbColl = query.getCollection();
    final MapReduceCommand cmd = new MapReduceCommand(dbColl, baseCommand.getMap(), baseCommand.getReduce(), baseCommand.getOutputTarget(), outType, query.getQueryObject());
    cmd.setFinalize(baseCommand.getFinalize());
    cmd.setScope(baseCommand.getScope());
    if (query.getLimit() > 0) {
        cmd.setLimit(query.getLimit());
    }
    if (query.getSortObject() != null) {
        cmd.setSort(query.getSortObject());
    }
    if (LOG.isTraceEnabled()) {
        LOG.info("Executing " + cmd.toString());
    }
    final EntityCache cache = createCache();
    MapreduceResults<T> results = new MapreduceResults<T>(dbColl.mapReduce(baseCommand));
    results.setType(type);
    if (MapreduceType.INLINE.equals(type)) {
        results.setInlineRequiredOptions(this, outputType, getMapper(), cache);
    } else {
        results.setQuery(newQuery(outputType, getDB().getCollection(results.getOutputCollectionName())));
    }
    return results;
}
Also used : DBCollection(com.mongodb.DBCollection) QueryException(org.mongodb.morphia.query.QueryException) EntityCache(org.mongodb.morphia.mapping.cache.EntityCache) MapReduceCommand(com.mongodb.MapReduceCommand) OutputType(com.mongodb.MapReduceCommand.OutputType)

Example 28 with DBCollection

use of com.mongodb.DBCollection in project morphia by mongodb.

the class DatastoreImpl method findAndModify.

@Override
public <T> T findAndModify(final Query<T> query, final UpdateOperations<T> operations, final FindAndModifyOptions options) {
    DBCollection dbColl = query.getCollection();
    // TODO remove this after testing.
    if (dbColl == null) {
        dbColl = getCollection(query.getEntityClass());
    }
    if (LOG.isTraceEnabled()) {
        LOG.info("Executing findAndModify(" + dbColl.getName() + ") with update ");
    }
    updateForVersioning(query, operations);
    DBObject res = dbColl.findAndModify(query.getQueryObject(), options.copy().sort(query.getSortObject()).projection(query.getFieldsObject()).update(((UpdateOpsImpl<T>) operations).getOps()).getOptions());
    return res == null ? null : mapper.fromDBObject(this, query.getEntityClass(), res, createCache());
}
Also used : DBCollection(com.mongodb.DBCollection) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject)

Example 29 with DBCollection

use of com.mongodb.DBCollection in project morphia by mongodb.

the class DatastoreImpl method merge.

@Override
@SuppressWarnings("unchecked")
public <T> Key<T> merge(final T entity, final WriteConcern wc) {
    T unwrapped = entity;
    final LinkedHashMap<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>();
    final DBObject dbObj = mapper.toDBObject(unwrapped, involvedObjects);
    final Key<T> key = mapper.getKey(unwrapped);
    unwrapped = ProxyHelper.unwrap(unwrapped);
    final Object id = mapper.getId(unwrapped);
    if (id == null) {
        throw new MappingException("Could not get id for " + unwrapped.getClass().getName());
    }
    // remove (immutable) _id field for update.
    final Object idValue = dbObj.get(Mapper.ID_KEY);
    dbObj.removeField(Mapper.ID_KEY);
    WriteResult wr;
    final MappedClass mc = mapper.getMappedClass(unwrapped);
    final DBCollection dbColl = getCollection(unwrapped);
    // try to do an update if there is a @Version field
    wr = tryVersionedUpdate(dbColl, unwrapped, dbObj, idValue, new InsertOptions().writeConcern(wc), mc);
    if (wr == null) {
        final Query<T> query = (Query<T>) createQuery(unwrapped.getClass()).filter(Mapper.ID_KEY, id);
        wr = update(query, new BasicDBObject("$set", dbObj), false, false, wc).getWriteResult();
    }
    final UpdateResults res = new UpdateResults(wr);
    if (res.getUpdatedCount() == 0) {
        throw new UpdateException("Nothing updated");
    }
    dbObj.put(Mapper.ID_KEY, idValue);
    postSaveOperations(Collections.<Object>singletonList(entity), involvedObjects, dbColl, false);
    return key;
}
Also used : Query(org.mongodb.morphia.query.Query) MappedClass(org.mongodb.morphia.mapping.MappedClass) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) UpdateResults(org.mongodb.morphia.query.UpdateResults) LinkedHashMap(java.util.LinkedHashMap) MappingException(org.mongodb.morphia.mapping.MappingException) DBCollection(com.mongodb.DBCollection) BasicDBObject(com.mongodb.BasicDBObject) WriteResult(com.mongodb.WriteResult) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) UpdateException(org.mongodb.morphia.query.UpdateException)

Example 30 with DBCollection

use of com.mongodb.DBCollection in project morphia by mongodb.

the class DatastoreImpl method mapReduce.

@Override
public <T> MapreduceResults<T> mapReduce(final MapReduceOptions<T> options) {
    DBCollection collection = options.getQuery().getCollection();
    final EntityCache cache = createCache();
    MapreduceResults<T> results = new MapreduceResults<T>(collection.mapReduce(options.toCommand(getMapper())));
    results.setOutputType(options.getOutputType());
    if (OutputType.INLINE.equals(options.getOutputType())) {
        results.setInlineRequiredOptions(this, options.getResultType(), getMapper(), cache);
    } else {
        results.setQuery(newQuery(options.getResultType(), getDB().getCollection(results.getOutputCollectionName())));
    }
    return results;
}
Also used : DBCollection(com.mongodb.DBCollection) EntityCache(org.mongodb.morphia.mapping.cache.EntityCache)

Aggregations

DBCollection (com.mongodb.DBCollection)165 DBObject (com.mongodb.DBObject)90 BasicDBObject (com.mongodb.BasicDBObject)86 Test (org.junit.Test)69 UsingDataSet (com.lordofthejars.nosqlunit.annotation.UsingDataSet)29 DBCursor (com.mongodb.DBCursor)23 MongoException (com.mongodb.MongoException)22 DB (com.mongodb.DB)20 BasicDBObjectBuilder (com.mongodb.BasicDBObjectBuilder)17 FailedDBOperationException (edu.umass.cs.gnscommon.exceptions.server.FailedDBOperationException)12 JSONObject (org.json.JSONObject)12 MongoClientURI (com.mongodb.MongoClientURI)11 QueryBuilder (com.mongodb.QueryBuilder)10 List (java.util.List)10 Map (java.util.Map)10 Stopwatch (com.google.common.base.Stopwatch)9 WriteResult (com.mongodb.WriteResult)9 HashMap (java.util.HashMap)9 IOException (java.io.IOException)8 ArrayList (java.util.ArrayList)8