List of usage examples for com.mongodb CommandResult get
public Object get(final String key)
From source file:org.slc.sli.ingestion.util.MongoCommander.java
License:Apache License
/** * get list of the shards/* w w w . j ava 2s . c om*/ * @param dbConn * @return */ private static List<String> getShards(DB dbConn) { List<String> shards = new ArrayList<String>(); DBObject listShardsCmd = new BasicDBObject("listShards", 1); CommandResult res = dbConn.command(listShardsCmd); if (!res.ok()) { LOG.error("Error getting shards for {}: {}", dbConn, res.getErrorMessage()); } BasicDBList listShards = (BasicDBList) res.get("shards"); //Only get shards for sharding mongo if (listShards != null) { ListIterator<Object> iter = listShards.listIterator(); while (iter.hasNext()) { BasicDBObject shard = (BasicDBObject) iter.next(); shards.add(shard.getString(ID)); } } return shards; }
From source file:org.springframework.data.mongodb.core.MongoTemplate.java
License:Apache License
@SuppressWarnings("unchecked") public <T> GeoResults<T> geoNear(NearQuery near, Class<T> entityClass, String collectionName) { if (near == null) { throw new InvalidDataAccessApiUsageException("NearQuery must not be null!"); }/*from w ww . j av a 2 s. co m*/ if (entityClass == null) { throw new InvalidDataAccessApiUsageException("Entity class must not be null!"); } String collection = StringUtils.hasText(collectionName) ? collectionName : determineCollectionName(entityClass); DBObject nearDbObject = near.toDBObject(); BasicDBObject command = new BasicDBObject("geoNear", collection); command.putAll(nearDbObject); if (nearDbObject.containsField("query")) { DBObject query = (DBObject) nearDbObject.get("query"); command.put("query", queryMapper.getMappedObject(query, getPersistentEntity(entityClass))); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Executing geoNear using: {} for class: {} in collection: {}", serializeToJsonSafely(command), entityClass, collectionName); } CommandResult commandResult = executeCommand(command, this.readPreference); List<Object> results = (List<Object>) commandResult.get("results"); results = results == null ? Collections.emptyList() : results; DbObjectCallback<GeoResult<T>> callback = new GeoNearResultDbObjectCallback<T>( new ReadDbObjectCallback<T>(mongoConverter, entityClass, collectionName), near.getMetric()); List<GeoResult<T>> result = new ArrayList<GeoResult<T>>(results.size()); int index = 0; int elementsToSkip = near.getSkip() != null ? near.getSkip() : 0; for (Object element : results) { /* * As MongoDB currently (2.4.4) doesn't support the skipping of elements in near queries * we skip the elements ourselves to avoid at least the document 2 object mapping overhead. * * @see https://jira.mongodb.org/browse/SERVER-3925 */ if (index >= elementsToSkip) { result.add(callback.doWith((DBObject) element)); } index++; } if (elementsToSkip > 0) { // as we skipped some elements we have to calculate the averageDistance ourselves: return new GeoResults<T>(result, near.getMetric()); } GeoCommandStatistics stats = GeoCommandStatistics.from(commandResult); return new GeoResults<T>(result, new Distance(stats.getAverageDistance(), near.getMetric())); }
From source file:org.springframework.data.mongodb.core.MongoTemplate.java
License:Apache License
public <T> GroupByResults<T> group(Criteria criteria, String inputCollectionName, GroupBy groupBy, Class<T> entityClass) { DBObject dbo = groupBy.getGroupByObject(); dbo.put("ns", inputCollectionName); if (criteria == null) { dbo.put("cond", null); } else {//from w w w . j av a 2 s .co m dbo.put("cond", queryMapper.getMappedObject(criteria.getCriteriaObject(), null)); } // If initial document was a JavaScript string, potentially loaded by Spring's Resource abstraction, load it and // convert to DBObject if (dbo.containsField("initial")) { Object initialObj = dbo.get("initial"); if (initialObj instanceof String) { String initialAsString = replaceWithResourceIfNecessary((String) initialObj); dbo.put("initial", JSON.parse(initialAsString)); } } if (dbo.containsField("$reduce")) { dbo.put("$reduce", replaceWithResourceIfNecessary(dbo.get("$reduce").toString())); } if (dbo.containsField("$keyf")) { dbo.put("$keyf", replaceWithResourceIfNecessary(dbo.get("$keyf").toString())); } if (dbo.containsField("finalize")) { dbo.put("finalize", replaceWithResourceIfNecessary(dbo.get("finalize").toString())); } DBObject commandObject = new BasicDBObject("group", dbo); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Executing Group with DBObject [{}]", serializeToJsonSafely(commandObject)); } CommandResult commandResult = executeCommand(commandObject, getDb().getOptions()); handleCommandError(commandResult, commandObject); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Group command result = [{}]", commandResult); } @SuppressWarnings("unchecked") Iterable<DBObject> resultSet = (Iterable<DBObject>) commandResult.get("retval"); List<T> mappedResults = new ArrayList<T>(); DbObjectCallback<T> callback = new ReadDbObjectCallback<T>(mongoConverter, entityClass, inputCollectionName); for (DBObject dbObject : resultSet) { mappedResults.add(callback.doWith(dbObject)); } return new GroupByResults<T>(mappedResults, commandResult); }
From source file:org.springframework.data.mongodb.core.MongoTemplate.java
License:Apache License
/** * Returns the potentially mapped results of the given {@commandResult} contained some. * /*from ww w .j ava 2 s . c o m*/ * @param outputType * @param commandResult * @return */ private <O> List<O> returnPotentiallyMappedResults(Class<O> outputType, CommandResult commandResult, String collectionName) { @SuppressWarnings("unchecked") Iterable<DBObject> resultSet = (Iterable<DBObject>) commandResult.get("result"); if (resultSet == null) { return Collections.emptyList(); } DbObjectCallback<O> callback = new UnwrapAndReadDbObjectCallback<O>(mongoConverter, outputType, collectionName); List<O> mappedResults = new ArrayList<O>(); for (DBObject dbObject : resultSet) { mappedResults.add(callback.doWith(dbObject)); } return mappedResults; }
From source file:org.springframework.data.mongodb.test.util.MongoVersionRule.java
License:Apache License
private void initCurrentVersion() { if (currentVersion == null) { try {//from w w w.ja v a2 s . c o m MongoClient client; client = new MongoClient(host, port); DB db = client.getDB("test"); CommandResult result = db.command(new BasicDBObjectBuilder().add("buildInfo", 1).get()); this.currentVersion = Version.parse(result.get("version").toString()); } catch (Exception e) { e.printStackTrace(); } } }
From source file:org.springframework.datastore.mapping.mongo.engine.MongoEntityPersister.java
License:Apache License
@Override protected Object generateIdentifier(final PersistentEntity persistentEntity, final DBObject nativeEntry) { return mongoTemplate.execute(new DbCallback<Object>() { @Override//from www. j a v a2 s . c om public Object doInDB(DB con) throws MongoException, DataAccessException { String collectionName = getCollectionName(persistentEntity, nativeEntry); DBCollection dbCollection = con.getCollection(collectionName + NEXT_ID_SUFFIX); // If there is a numeric identifier then we need to rely on optimistic concurrency controls to obtain a unique identifer // sequence. If the identifier is not numeric then we assume BSON ObjectIds. if (hasNumericalIdentifier) { while (true) { DBCursor result = dbCollection.find().sort(new BasicDBObject(MONGO_ID_FIELD, -1)).limit(1); long nextId; if (result.hasNext()) { final Long current = getMappingContext().getConversionService() .convert(result.next().get(MONGO_ID_FIELD), Long.class); nextId = current + 1; } else { nextId = 1; } nativeEntry.put(MONGO_ID_FIELD, nextId); final WriteResult writeResult = dbCollection.insert(nativeEntry); final CommandResult lastError = writeResult.getLastError(); if (lastError.ok()) { break; } else { final Object code = lastError.get("code"); // duplicate key error try again if (code != null && code.equals(11000)) { continue; } break; } } return nativeEntry.get(MONGO_ID_FIELD); } else { ObjectId objectId = ObjectId.get(); if (ObjectId.class.isAssignableFrom(persistentEntity.getIdentity().getType())) { nativeEntry.put(MONGO_ID_FIELD, objectId); return objectId; } else { String stringId = objectId.toString(); nativeEntry.put(MONGO_ID_FIELD, stringId); return stringId; } } } }); }