List of usage examples for com.mongodb DBObject containsField
boolean containsField(String s);
From source file:org.springframework.data.mongodb.core.convert.MappingMongoConverter.java
License:Apache License
protected void writeInternal(Object obj, final DBObject dbo, MongoPersistentEntity<?> entity) { if (obj == null) { return;//from w w w. j a v a 2 s. c o m } if (null == entity) { throw new MappingException("No mapping metadata found for entity of type " + obj.getClass().getName()); } final PersistentPropertyAccessor accessor = entity.getPropertyAccessor(obj); final MongoPersistentProperty idProperty = entity.getIdProperty(); if (!dbo.containsField("_id") && null != idProperty) { try { Object id = accessor.getProperty(idProperty); dbo.put("_id", idMapper.convertId(id)); } catch (ConversionException ignored) { } } // Write the properties entity.doWithProperties(new PropertyHandler<MongoPersistentProperty>() { public void doWithPersistentProperty(MongoPersistentProperty prop) { if (prop.equals(idProperty) || !prop.isWritable()) { return; } Object propertyObj = accessor.getProperty(prop); if (null != propertyObj) { if (!conversions.isSimpleType(propertyObj.getClass())) { writePropertyInternal(propertyObj, dbo, prop); } else { writeSimpleInternal(propertyObj, dbo, prop); } } } }); entity.doWithAssociations(new AssociationHandler<MongoPersistentProperty>() { public void doWithAssociation(Association<MongoPersistentProperty> association) { MongoPersistentProperty inverseProp = association.getInverse(); Object propertyObj = accessor.getProperty(inverseProp); if (null != propertyObj) { writePropertyInternal(propertyObj, dbo, inverseProp); } } }); }
From source file:org.springframework.data.mongodb.core.convert.QueryMapper.java
License:Apache License
private void mapMetaAttributes(DBObject source, MongoPersistentEntity<?> entity, MetaMapping metaMapping) { if (entity == null || source == null) { return;/*www. ja v a 2s . co m*/ } if (entity.hasTextScoreProperty() && !MetaMapping.IGNORE.equals(metaMapping)) { MongoPersistentProperty textScoreProperty = entity.getTextScoreProperty(); if (MetaMapping.FORCE.equals(metaMapping) || (MetaMapping.WHEN_PRESENT.equals(metaMapping) && source.containsField(textScoreProperty.getFieldName()))) { source.putAll(getMappedTextScoreField(textScoreProperty)); } } }
From source file:org.springframework.data.mongodb.core.convert.QueryMapper.java
License:Apache License
/** * Returns the mapped value for the given source object assuming it's a value for the given * {@link MongoPersistentProperty}./*www. ja va 2 s . co m*/ * * @param value the source object to be mapped * @param property the property the value is a value for * @param newKey the key the value will be bound to eventually * @return */ protected Object getMappedValue(Field documentField, Object value) { if (documentField.isIdField()) { if (isDBObject(value)) { DBObject valueDbo = (DBObject) value; DBObject resultDbo = new BasicDBObject(valueDbo.toMap()); if (valueDbo.containsField("$in") || valueDbo.containsField("$nin")) { String inKey = valueDbo.containsField("$in") ? "$in" : "$nin"; List<Object> ids = new ArrayList<Object>(); for (Object id : (Iterable<?>) valueDbo.get(inKey)) { ids.add(convertId(id)); } resultDbo.put(inKey, ids.toArray(new Object[ids.size()])); } else if (valueDbo.containsField("$ne")) { resultDbo.put("$ne", convertId(valueDbo.get("$ne"))); } else { return getMappedObject(resultDbo, null); } return resultDbo; } else { return convertId(value); } } if (isNestedKeyword(value)) { return getMappedKeyword(new Keyword((DBObject) value), null); } if (isAssociationConversionNecessary(documentField, value)) { return convertAssociation(value, documentField); } return convertSimpleOrDBObject(value, documentField.getPropertyEntity()); }
From source file:org.springframework.data.mongodb.core.DefaultIndexOperations.java
License:Apache License
public List<IndexInfo> getIndexInfo() { return mongoOperations.execute(collectionName, new CollectionCallback<List<IndexInfo>>() { public List<IndexInfo> doInCollection(DBCollection collection) throws MongoException, DataAccessException { List<DBObject> dbObjectList = collection.getIndexInfo(); return getIndexData(dbObjectList); }/* w w w .jav a 2 s .c om*/ private List<IndexInfo> getIndexData(List<DBObject> dbObjectList) { List<IndexInfo> indexInfoList = new ArrayList<IndexInfo>(); for (DBObject ix : dbObjectList) { DBObject keyDbObject = (DBObject) ix.get("key"); int numberOfElements = keyDbObject.keySet().size(); List<IndexField> indexFields = new ArrayList<IndexField>(numberOfElements); for (String key : keyDbObject.keySet()) { Object value = keyDbObject.get(key); if (TWO_D_IDENTIFIERS.contains(value)) { indexFields.add(IndexField.geo(key)); } else if ("text".equals(value)) { DBObject weights = (DBObject) ix.get("weights"); for (String fieldName : weights.keySet()) { indexFields.add(IndexField.text(fieldName, Float.valueOf(weights.get(fieldName).toString()))); } } else { Double keyValue = new Double(value.toString()); if (ONE.equals(keyValue)) { indexFields.add(IndexField.create(key, ASC)); } else if (MINUS_ONE.equals(keyValue)) { indexFields.add(IndexField.create(key, DESC)); } } } String name = ix.get("name").toString(); boolean unique = ix.containsField("unique") ? (Boolean) ix.get("unique") : false; boolean dropDuplicates = ix.containsField("dropDups") ? (Boolean) ix.get("dropDups") : false; boolean sparse = ix.containsField("sparse") ? (Boolean) ix.get("sparse") : false; String language = ix.containsField("default_language") ? (String) ix.get("default_language") : ""; indexInfoList.add(new IndexInfo(indexFields, name, unique, dropDuplicates, sparse, language)); } return indexInfoList; } }); }
From source file:org.springframework.data.mongodb.core.index.IndexInfo.java
License:Apache License
/** * Creates new {@link IndexInfo} parsing required properties from the given {@literal sourceDocument}. * * @param sourceDocument// ww w . j a v a 2 s . c o m * @return * @since 1.10 */ public static IndexInfo indexInfoOf(DBObject sourceDocument) { DBObject keyDbObject = (DBObject) sourceDocument.get("key"); int numberOfElements = keyDbObject.keySet().size(); List<IndexField> indexFields = new ArrayList<IndexField>(numberOfElements); for (String key : keyDbObject.keySet()) { Object value = keyDbObject.get(key); if (TWO_D_IDENTIFIERS.contains(value)) { indexFields.add(IndexField.geo(key)); } else if ("text".equals(value)) { DBObject weights = (DBObject) sourceDocument.get("weights"); for (String fieldName : weights.keySet()) { indexFields.add(IndexField.text(fieldName, Float.valueOf(weights.get(fieldName).toString()))); } } else { Double keyValue = new Double(value.toString()); if (ONE.equals(keyValue)) { indexFields.add(IndexField.create(key, ASC)); } else if (MINUS_ONE.equals(keyValue)) { indexFields.add(IndexField.create(key, DESC)); } } } String name = sourceDocument.get("name").toString(); boolean unique = sourceDocument.containsField("unique") ? (Boolean) sourceDocument.get("unique") : false; boolean dropDuplicates = sourceDocument.containsField("dropDups") ? (Boolean) sourceDocument.get("dropDups") : false; boolean sparse = sourceDocument.containsField("sparse") ? (Boolean) sourceDocument.get("sparse") : false; String language = sourceDocument.containsField("default_language") ? (String) sourceDocument.get("default_language") : ""; String partialFilter = sourceDocument.containsField("partialFilterExpression") ? sourceDocument.get("partialFilterExpression").toString() : ""; IndexInfo info = new IndexInfo(indexFields, name, unique, dropDuplicates, sparse, language); info.partialFilterExpression = partialFilter; return info; }
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 . jav 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
private boolean dbObjectContainsVersionProperty(DBObject dbObject, MongoPersistentEntity<?> persistentEntity) { if (persistentEntity == null || !persistentEntity.hasVersionProperty()) { return false; }//from w ww. j a v a 2s . com return dbObject.containsField(persistentEntity.getVersionProperty().getFieldName()); }
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 ww w . j a v a2s. c o 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.QueryMapper.java
License:Apache License
/** * Replaces the property keys used in the given {@link DBObject} with the appropriate keys by using the * {@link PersistentEntity} metadata.//from w w w.j a v a 2 s . c om * * @param query must not be {@literal null}. * @param entity can be {@literal null}. * @return */ public DBObject getMappedObject(DBObject query, MongoPersistentEntity<?> entity) { DBObject newDbo = new BasicDBObject(); for (String key : query.keySet()) { String newKey = key; Object value = query.get(key); if (isIdKey(key, entity)) { if (value instanceof DBObject) { DBObject valueDbo = (DBObject) value; if (valueDbo.containsField("$in") || valueDbo.containsField("$nin")) { String inKey = valueDbo.containsField("$in") ? "$in" : "$nin"; List<Object> ids = new ArrayList<Object>(); for (Object id : (Iterable<?>) valueDbo.get(inKey)) { ids.add(convertId(id)); } valueDbo.put(inKey, ids.toArray(new Object[ids.size()])); } else if (valueDbo.containsField("$ne")) { valueDbo.put("$ne", convertId(valueDbo.get("$ne"))); } else { value = getMappedObject((DBObject) value, null); } } else { value = convertId(value); } newKey = "_id"; } else if (key.matches(N_OR_PATTERN)) { // $or/$nor Iterable<?> conditions = (Iterable<?>) value; BasicBSONList newConditions = new BasicBSONList(); Iterator<?> iter = conditions.iterator(); while (iter.hasNext()) { newConditions.add(getMappedObject((DBObject) iter.next(), entity)); } value = newConditions; } newDbo.put(newKey, convertSimpleOrDBObject(value, null)); } return newDbo; }
From source file:tango.mongo.MongoConnector.java
License:Open Source License
public synchronized ArrayList<String> getNucSettings() { DBCursor cur = nucleusSettings.find().sort(new BasicDBObject("name", 1)); ArrayList<String> res = new ArrayList<String>(cur.count()); while (cur.hasNext()) { DBObject o = cur.next(); if (o.containsField("name")) { res.add(o.get("name").toString()); }/*ww w . j av a2s. c om*/ } cur.close(); return res; }