List of usage examples for com.mongodb DBObject putAll
void putAll(BSONObject o);
From source file:org.eclipselabs.mongoemf.query.simple.SimpleQueryEngine.java
License:Open Source License
private DBObject buildDBObjectQuery(Expression expression) { final DBObject dbObject = new BasicDBObject(); if (expression != null) { new QuerySwitch<Object>() { Object getValue(Literal literal) { return literal.getValue() == null ? literal.getLiteralValue() : literal.getValue(); }/*from w w w.j a v a 2s. c o m*/ @Override public Object caseBinaryOperation(BinaryOperation binaryOperation) { Expression leftOperand = binaryOperation.getLeftOperand(); String operator = binaryOperation.getOperator(); if ("==".equals(operator)) { Expression rightOperand = binaryOperation.getRightOperand(); String property = ExpressionBuilder.toString(leftOperand); if (Keywords.ID_KEY.equals(property)) { dbObject.put(property, new ObjectId(((Literal) rightOperand).getLiteralValue())); } else if (rightOperand instanceof Literal) { dbObject.put(property, getValue((Literal) rightOperand)); } else if ("null".equals(ExpressionBuilder.toString(rightOperand))) { DBObject notExists = new BasicDBObject(); notExists.put("$exists", Boolean.FALSE); dbObject.put(property, notExists); } else { // TODO: What to do? } } else if ("!=".equals(operator)) { Expression rightOperand = binaryOperation.getRightOperand(); String property = ExpressionBuilder.toString(leftOperand); if (rightOperand instanceof Literal) { DBObject notEqual = new BasicDBObject(); notEqual.put("$ne", getValue((Literal) rightOperand)); dbObject.put(property, notEqual); } else if ("null".equals(ExpressionBuilder.toString(rightOperand))) { DBObject exists = new BasicDBObject(); exists.put("$exists", Boolean.TRUE); dbObject.put(property, exists); } else { // TODO: What to do? } } else if ("<".equals(operator) || "<=".equals(operator) || ">".equals(operator) || ">=".equals(operator)) { Expression rightOperand = binaryOperation.getRightOperand(); String property = ExpressionBuilder.toString(leftOperand); if (rightOperand instanceof Literal) { DBObject compare = new BasicDBObject(); compare.put( "<".equals(operator) ? QueryOperators.LT : "<=".equals(operator) ? QueryOperators.LTE : ">".equals(operator) ? QueryOperators.GT : QueryOperators.GTE, getValue((Literal) rightOperand)); dbObject.put(property, compare); } else { // TODO: What to do? } } else if ("||".equals(operator)) { DBObject leftObject = buildDBObjectQuery(leftOperand); DBObject rightObject = buildDBObjectQuery(binaryOperation.getRightOperand()); @SuppressWarnings("unchecked") List<Object> or = (List<Object>) leftObject.get("$or"); if (or != null) { or.add(rightObject); dbObject.putAll(leftObject); } else { or = new ArrayList<Object>(); or.add(leftObject); or.add(rightObject); dbObject.put("$or", or); } } else if ("&&".equals(operator)) { dbObject.putAll(buildDBObjectQuery(leftOperand)); DBObject rightObject = buildDBObjectQuery(binaryOperation.getRightOperand()); for (String field : rightObject.keySet()) { Object rightValue = rightObject.get(field); Object leftValue = dbObject.get(field); if (leftValue instanceof DBObject) { DBObject leftDBObject = (DBObject) leftValue; if (rightValue instanceof DBObject) { DBObject rightDBObject = (DBObject) rightValue; if (leftDBObject.containsField("$nin") && rightDBObject.containsField("$ne")) { @SuppressWarnings("unchecked") List<Object> values = (List<Object>) leftDBObject.get("$nin"); values.add(rightDBObject.get("$ne")); } else if (leftDBObject.containsField("$ne") && rightDBObject.containsField("$ne")) { DBObject nin = new BasicDBObject(); List<Object> values = new ArrayList<Object>(); values.add(leftDBObject.get("$ne")); values.add(rightDBObject.get("$ne")); nin.put("$nin", values); dbObject.put(field, nin); } else { leftDBObject.putAll(rightDBObject); } } else { Object all = leftDBObject.get("$all"); if (all instanceof List<?>) { @SuppressWarnings("unchecked") List<Object> allList = (List<Object>) all; allList.add(rightValue); } else { // What to do? } } } else if (leftValue instanceof List<?>) { @SuppressWarnings("unchecked") List<Object> leftListValue = (List<Object>) leftValue; if (rightValue instanceof List<?>) { leftListValue.addAll((List<?>) rightValue); } else { leftListValue.add(rightValue); } } else if (leftValue != null) { if (rightValue instanceof List<?>) { @SuppressWarnings("unchecked") List<Object> rightListValue = (List<Object>) rightValue; rightListValue.add(0, leftValue); dbObject.put(field, rightListValue); } else { List<Object> listValue = new ArrayList<Object>(); listValue.add(leftValue); listValue.add(rightValue); DBObject in = new BasicDBObject("$all", listValue); dbObject.put(field, in); } } else { dbObject.put(field, rightValue); } } } return null; } }.doSwitch(expression); } return dbObject; }
From source file:org.grails.datastore.mapping.mongo.MongoDatastore.java
License:Apache License
/** * Indexes any properties that are mapped with index:true * @param entity The entity/*w w w . ja va2 s.c o m*/ * @param template The template */ protected void initializeIndices(final PersistentEntity entity, final MongoTemplate template) { template.execute(new DbCallback<Object>() { @SuppressWarnings({ "unchecked", "rawtypes" }) public Object doInDB(DB db) throws MongoException, DataAccessException { final DBCollection collection = db.getCollection(getCollectionName(entity)); final ClassMapping<MongoCollection> classMapping = entity.getMapping(); if (classMapping != null) { final MongoCollection mappedForm = classMapping.getMappedForm(); if (mappedForm != null) { for (Map compoundIndex : mappedForm.getCompoundIndices()) { DBObject indexDef = new BasicDBObject(compoundIndex); collection.ensureIndex(indexDef); } } } for (PersistentProperty<MongoAttribute> property : entity.getPersistentProperties()) { final boolean indexed = isIndexed(property); if (indexed) { final MongoAttribute mongoAttributeMapping = property.getMapping().getMappedForm(); DBObject dbObject = new BasicDBObject(); final String fieldName = getMongoFieldNameForProperty(property); dbObject.put(fieldName, 1); DBObject options = new BasicDBObject(); if (mongoAttributeMapping != null) { Map attributes = mongoAttributeMapping.getIndexAttributes(); if (attributes != null) { attributes = new HashMap(attributes); if (attributes.containsKey(MongoAttribute.INDEX_TYPE)) { dbObject.put(fieldName, attributes.remove(MongoAttribute.INDEX_TYPE)); } options.putAll(attributes); } } if (options.toMap().isEmpty()) { collection.ensureIndex(dbObject); } else { collection.ensureIndex(dbObject, options); } } } return null; } String getMongoFieldNameForProperty(PersistentProperty<MongoAttribute> property) { PropertyMapping<MongoAttribute> pm = property.getMapping(); String propKey = null; if (pm.getMappedForm() != null) { propKey = pm.getMappedForm().getField(); } if (propKey == null) { propKey = property.getName(); } return propKey; } }); }
From source file:org.iternine.jeppetto.dao.mongodb.enhance.DBObjectUtil.java
License:Apache License
public static Object fromObject(Class<?> type, final Object o, final Class<?>... typeParameters) { if (o == null) { return null; } else if (type.isAssignableFrom(o.getClass())) { if (List.class.isAssignableFrom(type)) { return fromList(o, typeParameters); } else if (Map.class.isAssignableFrom(type)) { return fromMap(o, typeParameters); } else if (Set.class.isAssignableFrom(type)) { return fromSet(o, typeParameters); } else if (Iterable.class.isAssignableFrom(type)) { return fromList(o, typeParameters); }/* w ww . jav a 2 s . c om*/ return type.cast(o); } else if (Iterable.class.isAssignableFrom(o.getClass()) && Set.class.isAssignableFrom(type)) { return fromSet(o, typeParameters); } else if (o instanceof DBObject) { // TODO: validate works on nested objects of various types... DBObject copy = (DBObject) EnhancerHelper.getDirtyableDBObjectEnhancer(type).newInstance(); copy.putAll((DBObject) o); return copy; } else if (Enum.class.isAssignableFrom(type) && String.class.isAssignableFrom(o.getClass())) { // noinspection unchecked return Enum.valueOf((Class<Enum>) type, (String) o); } else if (BigDecimal.class == type && Number.class.isAssignableFrom(o.getClass())) { return BigDecimal.valueOf(((Number) o).doubleValue()); } else if (BigInteger.class == type && Number.class.isAssignableFrom(o.getClass())) { return BigInteger.valueOf(((Number) o).longValue()); } else { throw new RuntimeException("Not sure how to convert a " + o + " to a " + type.getSimpleName()); } }
From source file:org.jongo.util.BsonUtil.java
License:Apache License
public static BsonDocument bsonify(String json) throws IOException { Map map = OBJECT_MAPPER.readValue(jsonify(json), HashMap.class); DBObject dbo = new BasicDBObject(); dbo.putAll(map); return Bson.createDocument(dbo); }
From source file:org.mongoj.samples.service.persistence.CarPersistenceImpl.java
License:Open Source License
protected DBObject getDBObject(Car car) { DBObject dbObject = new BasicDBObject(); if (car.getId() != null) { dbObject.put("_id", new ObjectId(car.getId())); } else {//from w w w .j a va2 s.c om ObjectId id = new ObjectId(); dbObject.put("_id", id); car.setId(id.toString()); } dbObject.putAll(car.toMap()); return dbObject; }
From source file:org.mongoj.samples.service.persistence.UserPersistenceImpl.java
License:Open Source License
protected DBObject getDBObject(User user) { DBObject dbObject = new BasicDBObject(); if (user.getId() != null) { dbObject.put("_id", new ObjectId(user.getId())); } else {// www. j a va 2s . c om ObjectId id = new ObjectId(); dbObject.put("_id", id); user.setId(id.toString()); } dbObject.putAll(user.toMap()); return dbObject; }
From source file:org.mule.module.mongo.MongoCloudConnector.java
License:Open Source License
/** * Convert JSON to DBObject.// w ww . j a v a2s.c o m * <p/> * {@sample.xml ../../../doc/mongo-connector.xml.sample mongo:jsonToDbobject} * * @param input the input for this transformer * @return the converted {@link DBObject} */ @Transformer(sourceTypes = { String.class }) public static DBObject jsonToDbobject(final String input) { DBObject o = null; BSONObject bsonObj = null; Object obj = JSON.parse(input); if (obj instanceof BasicDBList) { BasicDBList basicList = (BasicDBList) obj; if (basicList.size() > 1) { for (int i = 0; i < basicList.size(); i++) { bsonObj = (BSONObject) basicList.get(0); @SuppressWarnings("rawtypes") Map entries = bsonObj.toMap(); if (i > 0) { o.putAll(entries); } else { o = new BasicDBObject(entries); } } } } else { o = (DBObject) obj; } return o; }
From source file:org.nuxeo.ecm.core.storage.mongodb.MongoDBRepository.java
License:Apache License
@Override public void updateState(String id, StateDiff diff, ChangeTokenUpdater changeTokenUpdater) { List<DBObject> updates = converter.diffToBson(diff); for (DBObject update : updates) { DBObject query = new BasicDBObject(idKey, id); if (changeTokenUpdater == null) { if (log.isTraceEnabled()) { log.trace("MongoDB: UPDATE " + id + ": " + update); }// w ww .j a va 2 s . c o m } else { // assume bson is identical to dbs internals // condition works even if value is null Map<String, Serializable> conditions = changeTokenUpdater.getConditions(); Map<String, Serializable> tokenUpdates = changeTokenUpdater.getUpdates(); if (update.containsField(MONGODB_SET)) { ((DBObject) update.get(MONGODB_SET)).putAll(tokenUpdates); } else { DBObject set = new BasicDBObject(); set.putAll(tokenUpdates); update.put(MONGODB_SET, set); } if (log.isTraceEnabled()) { log.trace("MongoDB: UPDATE " + id + ": IF " + conditions + " THEN " + update); } query.putAll(conditions); } WriteResult w = coll.update(query, update); if (w.getN() != 1) { log.trace("MongoDB: -> CONCURRENT UPDATE: " + id); throw new ConcurrentUpdateException(id); } // TODO dupe exception // throw new DocumentException("Missing: " + id); } }
From source file:org.opencb.opencga.storage.mongodb.alignment.CoverageMongoDBWriter.java
License:Apache License
private void secureInsert(DBObject query, DBObject object, String chromosome, int start, int size) { boolean documentExists = true; boolean fileExists = true; //Check if the document exists {/*from w ww.java 2 s. c om*/ QueryResult countId = collection.count(query); if (countId.getNumResults() == 1 && countId.getResultType().equals(Long.class.getCanonicalName())) { if ((Long) countId.getResult().get(0) < 1) { DBObject document = BasicDBObjectBuilder.start().append(FILES_FIELD, new BasicDBList()) .append(CHR_FIELD, chromosome).append(START_FIELD, start).append(SIZE_FIELD, size) .get(); document.putAll(query); //{_id:<chunkId>, files:[]} collection.insert(document, null); //Insert a document with empty files array. fileExists = false; } } else { logger.error(countId.getErrorMsg(), countId); } } if (documentExists) { //Check if the file exists BasicDBObject fileQuery = new BasicDBObject(FILES_FIELD + "." + FILE_ID_FIELD, fileId); fileQuery.putAll(query); QueryResult countFile = collection.count(fileQuery); if (countFile.getNumResults() == 1 && countFile.getResultType().equals(Long.class.getCanonicalName())) { if ((Long) countFile.getResult().get(0) < 1) { fileExists = false; } } else { logger.error(countFile.getErrorMsg(), countFile); } } if (fileExists) { BasicDBObject fileQuery = new BasicDBObject(FILES_FIELD + "." + FILE_ID_FIELD, fileId); fileQuery.putAll(query); BasicDBObject fileObject = new BasicDBObject(); for (String key : object.keySet()) { fileObject.put(FILES_FIELD + ".$." + key, object.get(key)); } // DBObject update = new BasicDBObject("$set", new BasicDBObject(FILES_FIELD, fileObject)); DBObject update = new BasicDBObject("$set", fileObject); //db.<collectionName>.update({_id:<chunkId> , "files.id":<fileId>}, {$set:{"files.$.<objKey>":<objValue>}}) collection.update(fileQuery, update, updateOptions); } else { BasicDBObject fileObject = new BasicDBObject(FILE_ID_FIELD, fileId); fileObject.putAll(object); DBObject update = new BasicDBObject("$addToSet", new BasicDBObject(FILES_FIELD, fileObject)); //db.<collectionName>.update({_id:<chunkId>} , {$addToSet:{files:{id:<fileId>, <object>}}}) collection.update(query, update, updateOptions); } }
From source file:org.opencb.opencga.storage.mongodb.variant.VariantMongoDBAdaptor.java
License:Apache License
/** * Two steps insertion:/*w ww. ja v a 2 s . c om*/ * First check that the variant and study exists making an update. * For those who doesn't exist, pushes a study with the file and genotype information * * The documents that throw a "dup key" exception are those variants that exist and have the study. * Then, only for those variants, make a second update. * * *An interesting idea would be to invert this actions depending on the number of already inserted variants. * * @param loadedSampleIds Other loaded sampleIds EXCEPT those that are going to be loaded * @param data Variants to insert */ QueryResult insert(List<Variant> data, int fileId, DBObjectToVariantConverter variantConverter, DBObjectToVariantSourceEntryConverter variantSourceEntryConverter, StudyConfiguration studyConfiguration, List<Integer> loadedSampleIds) { if (data.isEmpty()) { return new QueryResult("insertVariants"); } List<DBObject> queries = new ArrayList<>(data.size()); List<DBObject> updates = new ArrayList<>(data.size()); Set<String> nonInsertedVariants; String fileIdStr = Integer.toString(fileId); { nonInsertedVariants = new HashSet<>(); Map missingSamples = Collections.emptyMap(); String defaultGenotype = studyConfiguration.getAttributes() .getString(MongoDBVariantStorageManager.DEFAULT_GENOTYPE, ""); if (defaultGenotype.equals(DBObjectToSamplesConverter.UNKNOWN_GENOTYPE)) { logger.debug("Do not need fill gaps. DefaultGenotype is UNKNOWN_GENOTYPE({})."); } else if (!loadedSampleIds.isEmpty()) { missingSamples = new BasicDBObject(DBObjectToSamplesConverter.UNKNOWN_GENOTYPE, loadedSampleIds); // ?/? } for (Variant variant : data) { String id = variantConverter.buildStorageId(variant); for (VariantSourceEntry variantSourceEntry : variant.getSourceEntries().values()) { if (!variantSourceEntry.getFileId().equals(fileIdStr)) { continue; } int studyId = studyConfiguration.getStudyId(); DBObject study = variantSourceEntryConverter.convertToStorageType(variantSourceEntry); DBObject genotypes = (DBObject) study .get(DBObjectToVariantSourceEntryConverter.GENOTYPES_FIELD); if (genotypes != null) { //If genotypes is null, genotypes are not suppose to be loaded genotypes.putAll(missingSamples); //Add missing samples } DBObject push = new BasicDBObject(DBObjectToVariantConverter.STUDIES_FIELD, study); BasicDBObject update = new BasicDBObject().append("$push", push).append("$setOnInsert", variantConverter.convertToStorageType(variant)); if (variant.getIds() != null && !variant.getIds().isEmpty() && !variant.getIds().iterator().next().isEmpty()) { update.put("$addToSet", new BasicDBObject(DBObjectToVariantConverter.IDS_FIELD, new BasicDBObject("$each", variant.getIds()))); } // { _id: <variant_id>, "studies.sid": {$ne: <studyId> } } //If the variant exists and contains the study, this find will fail, will try to do the upsert, and throw a duplicated key exception. queries.add(new BasicDBObject("_id", id).append( DBObjectToVariantConverter.STUDIES_FIELD + "." + DBObjectToVariantSourceEntryConverter.STUDYID_FIELD, new BasicDBObject("$ne", studyId))); updates.add(update); } } QueryOptions options = new QueryOptions("upsert", true); options.put("multi", false); try { variantsCollection.update(queries, updates, options); } catch (BulkWriteException e) { for (BulkWriteError writeError : e.getWriteErrors()) { if (writeError.getCode() == 11000) { //Dup Key error code nonInsertedVariants.add(writeError.getMessage().split("dup key")[1].split("\"")[1]); } else { throw e; } } } queries.clear(); updates.clear(); } for (Variant variant : data) { variant.setAnnotation(null); String id = variantConverter.buildStorageId(variant); if (nonInsertedVariants != null && !nonInsertedVariants.contains(id)) { continue; //Already inserted variant } for (VariantSourceEntry variantSourceEntry : variant.getSourceEntries().values()) { if (!variantSourceEntry.getFileId().equals(fileIdStr)) { continue; } DBObject studyObject = variantSourceEntryConverter.convertToStorageType(variantSourceEntry); DBObject genotypes = (DBObject) studyObject .get(DBObjectToVariantSourceEntryConverter.GENOTYPES_FIELD); DBObject push = new BasicDBObject(); if (genotypes != null) { //If genotypes is null, genotypes are not suppose to be loaded for (String genotype : genotypes.keySet()) { push.put( DBObjectToVariantConverter.STUDIES_FIELD + ".$." + DBObjectToVariantSourceEntryConverter.GENOTYPES_FIELD + "." + genotype, new BasicDBObject("$each", genotypes.get(genotype))); } } else { push.put( DBObjectToVariantConverter.STUDIES_FIELD + ".$." + DBObjectToVariantSourceEntryConverter.GENOTYPES_FIELD, Collections.emptyMap()); } push.put( DBObjectToVariantConverter.STUDIES_FIELD + ".$." + DBObjectToVariantSourceEntryConverter.FILES_FIELD, ((List) studyObject.get(DBObjectToVariantSourceEntryConverter.FILES_FIELD)).get(0)); BasicDBObject update = new BasicDBObject(new BasicDBObject("$push", push)); queries.add(new BasicDBObject("_id", id).append( DBObjectToVariantConverter.STUDIES_FIELD + "." + DBObjectToVariantSourceEntryConverter.STUDYID_FIELD, studyConfiguration.getStudyId())); updates.add(update); } } if (queries.isEmpty()) { return new QueryResult(); } else { QueryOptions options = new QueryOptions("upsert", false); options.put("multi", false); return variantsCollection.update(queries, updates, options); } }