Java Code Examples for org.bson.Document#isEmpty()

The following examples show how to use org.bson.Document#isEmpty() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WhereCauseProcessor.java    From sql-to-mongo-db-query-converter with Apache License 2.0 6 votes vote down vote up
protected Object recurseFunctions(Document query, Object object, FieldType defaultFieldType, Map<String, FieldType> fieldNameToFieldTypeMapping) throws ParseException {
    if (Function.class.isInstance(object)) {
        Function function = (Function)object;
        query.put("$" + FunctionProcessor.transcriptFunctionName(function.getName()), recurseFunctions(new Document(), function.getParameters(), defaultFieldType, fieldNameToFieldTypeMapping));
    } else if (ExpressionList.class.isInstance(object)) {
        ExpressionList expressionList = (ExpressionList)object;
        List<Object> objectList = new ArrayList<>();
        for (Expression expression : expressionList.getExpressions()) {
            objectList.add(recurseFunctions(new Document(), expression, defaultFieldType, fieldNameToFieldTypeMapping));
        }
        return objectList.size() == 1 ? objectList.get(0) : objectList;
    } else if (Expression.class.isInstance(object)) {
        return SqlUtils.getValue((Expression)object, null, defaultFieldType, fieldNameToFieldTypeMapping);
    }

    return query.isEmpty() ? null : query;
}
 
Example 2
Source File: PropertiesStore.java    From EDDI with Apache License 2.0 6 votes vote down vote up
void mergeProperties(String userId, Properties newProperties) {
    Properties currentProperties = readProperties(userId);
    boolean create = false;
    if (currentProperties == null) {
        currentProperties = new Properties();
        currentProperties.put(USER_ID, userId);
        create = true;
    }

    currentProperties.putAll(newProperties);
    Document propertiesDocument = new Document(currentProperties);

    if (!propertiesDocument.isEmpty()) {
        if (create) {
            collection.insertOne(propertiesDocument);
        } else {
            collection.replaceOne(new Document(USER_ID, userId), propertiesDocument);
        }
    }
}
 
Example 3
Source File: Operations.java    From morphia with Apache License 2.0 6 votes vote down vote up
/**
 * @return the Document form of this instance
 * @morphia.internal
 */
Document toDocument() {
    versionUpdate();

    Document document = new Document();
    for (final Entry<String, List<OperationTarget>> entry : ops.entrySet()) {
        Document targets = new Document();
        for (OperationTarget operationTarget : entry.getValue()) {
            Object encode = operationTarget.encode(mapper);
            if (encode instanceof Document) {
                targets.putAll((Document) encode);
            } else {
                document.put(entry.getKey(), encode);
            }
        }
        if (!targets.isEmpty()) {
            document.put(entry.getKey(), targets);
        }
    }
    return document;
}
 
Example 4
Source File: MongoImpl.java    From tephra with MIT License 5 votes vote down vote up
@Override
public JSONObject findOne(String key, String collection, JSONObject where) {
    MongoCollection<Document> mc = getCollection(key, collection);
    if (mc == null)
        return new JSONObject();

    Document document = mc.find(toDocument(where)).first();

    return document == null || document.isEmpty() ? new JSONObject() : JSON.parseObject(document.toJson());
}
 
Example 5
Source File: GenericService.java    From HA-DB with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Document save(Document t, String collectionName) {
	if (!t.isEmpty()) {
		t.put(Opations.CREATED_FIELD, new Date()); // 创建时间
		t.put(Opations.UPDATED_FIELD, new Date()); // 更新时间
	}
	return super.save(t, collectionName);
}
 
Example 6
Source File: IndexHelper.java    From morphia with Apache License 2.0 5 votes vote down vote up
private void calculateWeights(final Index index, final com.mongodb.client.model.IndexOptions indexOptions) {
    Document weights = new Document();
    for (Field field : index.fields()) {
        if (field.weight() != -1) {
            if (field.type() != IndexType.TEXT) {
                throw new MappingException("Weight values only apply to text indexes: " + Arrays.toString(index.fields()));
            }
            weights.put(field.value(), field.weight());
        }
    }
    if (!weights.isEmpty()) {
        indexOptions.weights(weights);
    }
}
 
Example 7
Source File: QueryConverter.java    From sql-to-mongo-db-query-converter with Apache License 2.0 4 votes vote down vote up
public List<Document> generateAggSteps(MongoDBQueryHolder mongoDBQueryHolder, SQLCommandInfoHolder sqlCommandInfoHolder) {
    
    List<Document> documents = setUpStartPipeline(mongoDBQueryHolder);        
    
    if (mongoDBQueryHolder.getQuery() != null && mongoDBQueryHolder.getQuery().size() > 0) {
        documents.add(new Document("$match", mongoDBQueryHolder.getQuery()));
    }
    if(sqlCommandInfoHolder.getJoins() != null && !sqlCommandInfoHolder.getJoins().isEmpty()) {
    	documents.addAll(mongoDBQueryHolder.getJoinPipeline());
    }
    if(!sqlCommandInfoHolder.getGoupBys().isEmpty() || sqlCommandInfoHolder.isTotalGroup()) {
    	if(mongoDBQueryHolder.getProjection().get("_id") == null ) {//Generate _id with empty document
    		Document dgroup = new Document();
    		dgroup.put("_id", new Document());
    		for(Entry<String,Object> keyValue : mongoDBQueryHolder.getProjection().entrySet()) {
    			if(!keyValue.getKey().equals("_id")) {
    				dgroup.put(keyValue.getKey(),keyValue.getValue());
    			}
    		}
    		documents.add(new Document("$group", dgroup));
    	}
    	else {
    		documents.add(new Document("$group", mongoDBQueryHolder.getProjection()));
    	}
    	
    }
    if (mongoDBQueryHolder.getHaving() != null && mongoDBQueryHolder.getHaving().size() > 0 ){
        documents.add(new Document("$match",mongoDBQueryHolder.getHaving()));
    }
    if (mongoDBQueryHolder.getSort() != null && mongoDBQueryHolder.getSort().size() > 0) {
        documents.add(new Document("$sort", mongoDBQueryHolder.getSort()));
    }
    if (mongoDBQueryHolder.getOffset() != -1) {
        documents.add(new Document("$skip", mongoDBQueryHolder.getOffset()));
    }
    if (mongoDBQueryHolder.getLimit() != -1) {
        documents.add(new Document("$limit", mongoDBQueryHolder.getLimit()));
    }
    
    Document aliasProjection = mongoDBQueryHolder.getAliasProjection();
    if(!aliasProjection.isEmpty()) {//Alias Group by
    	documents.add(new Document("$project",aliasProjection));
    }
    
    if(sqlCommandInfoHolder.getGoupBys().isEmpty() && !sqlCommandInfoHolder.isTotalGroup() && !mongoDBQueryHolder.getProjection().isEmpty()) {//Alias no group
    	Document projection = mongoDBQueryHolder.getProjection();
    	documents.add(new Document("$project",projection));
    }

    return documents;
}
 
Example 8
Source File: MongoDBProcessor.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Override
protected void process(Record record, SingleLaneBatchMaker batchMaker) throws StageException {
  // Construct a document for lookup filter
  Document query = new Document();
  for (MongoDBFieldColumnMapping mapping: configBean.fieldMapping) {
    // if record doesn't have a field specified in the mapping, or value is null,
    // exclude the field from filter, instead of sending to error.
    if (record.has(mapping.sdcField) && record.get(mapping.sdcField) != null) {
      query.append(mapping.keyName, record.get(mapping.sdcField).getValue());
    }
  }
  // If all of the filters are missing in record, we cannot perform lookup.
  if (query.isEmpty()) {
    throw new OnRecordErrorException(Errors.MONGODB_42, record);
  }

  Optional<List<Map<String, Field>>> entry;
  try {
    entry = cache.get(query);
  } catch (ExecutionException e) {
    Throwables.propagateIfPossible(e.getCause(), StageException.class);
    throw new IllegalStateException(e); // The cache loader shouldn't throw anything that isn't a StageException.
  }

  if (entry.isPresent()) {
    List<Map<String, Field>> values = entry.get();
    switch (configBean.multipleValuesBehavior) {
      case FIRST_ONLY:
        setFieldsInRecord(record, values.get(0));
        batchMaker.addRecord(record);
        break;
      case SPLIT_INTO_MULTIPLE_RECORDS:
        for (Map<String, Field> lookupItem : values) {
          Record newRecord = getContext().cloneRecord(record);
          setFieldsInRecord(newRecord, lookupItem);
          batchMaker.addRecord(newRecord);
        }
        break;
      default:
        throw new IllegalStateException("Unknown multiple value behavior: " + configBean.multipleValuesBehavior);
    }
  } else {
    // No results
    switch (configBean.missingValuesBehavior) {
      case SEND_TO_ERROR:
        LOG.error(Errors.MONGODB_40.getMessage(), query.toJson());
        errorRecordHandler.onError(new OnRecordErrorException(record, Errors.MONGODB_40, query.toJson()));
        break;
      case PASS_RECORD_ON:
        batchMaker.addRecord(record);
        break;
      default:
        throw new IllegalStateException("Unknown missing value behavior: " + configBean.missingValuesBehavior);
    }
  }
}
 
Example 9
Source File: MongoDocumentStorage.java    From lumongo with Apache License 2.0 4 votes vote down vote up
public void getAssociatedDocuments(OutputStream outputstream, Document filter) throws IOException {
	Charset charset = Charset.forName("UTF-8");

	GridFSBucket gridFS = createGridFSConnection();
	GridFSFindIterable gridFSFiles = gridFS.find(filter);
	outputstream.write("{\n".getBytes(charset));
	outputstream.write(" \"associatedDocs\": [\n".getBytes(charset));

	boolean first = true;
	for (GridFSFile gridFSFile : gridFSFiles) {
		if (first) {
			first = false;
		}
		else {
			outputstream.write(",\n".getBytes(charset));
		}

		Document metadata = gridFSFile.getMetadata();

		String uniqueId = metadata.getString(DOCUMENT_UNIQUE_ID_KEY);
		String uniquieIdKeyValue = "  { \"uniqueId\": \"" + uniqueId + "\", ";
		outputstream.write(uniquieIdKeyValue.getBytes(charset));

		String filename = gridFSFile.getFilename();
		String filenameKeyValue = "\"filename\": \"" + filename + "\", ";
		outputstream.write(filenameKeyValue.getBytes(charset));

		Date uploadDate = gridFSFile.getUploadDate();
		String uploadDateKeyValue = "\"uploadDate\": {\"$date\":" + uploadDate.getTime() + "}";
		outputstream.write(uploadDateKeyValue.getBytes(charset));

		metadata.remove(TIMESTAMP);
		metadata.remove(COMPRESSED_FLAG);
		metadata.remove(DOCUMENT_UNIQUE_ID_KEY);
		metadata.remove(FILE_UNIQUE_ID_KEY);

		if (!metadata.isEmpty()) {
			String metaJson = metadata.toJson();
			String metaString = ", \"meta\": " + metaJson;
			outputstream.write(metaString.getBytes(charset));
		}

		outputstream.write(" }".getBytes(charset));

	}
	outputstream.write("\n ]\n}".getBytes(charset));
}