use of org.bson.BsonJavaScript in project mongo-java-driver by mongodb.
the class GroupCommand method toOperation.
GroupOperation<DBObject> toOperation(final MongoNamespace namespace, final DBObjectCodec codec) {
if (initial == null) {
throw new IllegalArgumentException("Group command requires an initial document for the aggregate result");
}
if (reduce == null) {
throw new IllegalArgumentException("Group command requires a reduce function for the aggregate result");
}
GroupOperation<DBObject> operation = new GroupOperation<DBObject>(namespace, new BsonJavaScript(reduce), new BsonDocumentWrapper<DBObject>(initial, codec), codec);
if (keys != null) {
operation.key(new BsonDocumentWrapper<DBObject>(keys, codec));
}
if (keyf != null) {
operation.keyFunction(new BsonJavaScript(keyf));
}
if (condition != null) {
operation.filter(new BsonDocumentWrapper<DBObject>(condition, codec));
}
if (finalize != null) {
operation.finalizeFunction(new BsonJavaScript(finalize));
}
operation.collation(collation);
return operation;
}
use of org.bson.BsonJavaScript in project querydsl by querydsl.
the class MongodbDocumentSerializer method visit.
@SuppressWarnings("unchecked")
@Override
public Object visit(Operation<?> expr, Void context) {
Operator op = expr.getOperator();
if (op == Ops.EQ) {
if (expr.getArg(0) instanceof Operation) {
Operation<?> lhs = (Operation<?>) expr.getArg(0);
if (lhs.getOperator() == Ops.COL_SIZE || lhs.getOperator() == Ops.ARRAY_SIZE) {
return asDocument(asDBKey(lhs, 0), asDocument("$size", asDBValue(expr, 1)));
} else {
throw new UnsupportedOperationException("Illegal operation " + expr);
}
} else if (expr.getArg(0) instanceof Path) {
Path<?> path = (Path<?>) expr.getArg(0);
Constant<?> constant = (Constant<?>) expr.getArg(1);
return asDocument(asDBKey(expr, 0), convert(path, constant));
}
} else if (op == Ops.STRING_IS_EMPTY) {
return asDocument(asDBKey(expr, 0), "");
} else if (op == Ops.AND) {
Queue<Map<Object, Object>> pendingDocuments = collectConnectorArgs("$and", expr);
List<Map<Object, Object>> unmergeableDocuments = new ArrayList<Map<Object, Object>>();
List<Map<Object, Object>> generatedDocuments = new ArrayList<Map<Object, Object>>();
while (!pendingDocuments.isEmpty()) {
Map<Object, Object> lhs = pendingDocuments.poll();
for (Map<Object, Object> rhs : pendingDocuments) {
Set<Object> lhs2 = new LinkedHashSet<Object>(lhs.keySet());
lhs2.retainAll(rhs.keySet());
if (lhs2.isEmpty()) {
lhs.putAll(rhs);
} else {
unmergeableDocuments.add(rhs);
}
}
generatedDocuments.add(lhs);
pendingDocuments = new LinkedList<Map<Object, Object>>(unmergeableDocuments);
unmergeableDocuments = new LinkedList<Map<Object, Object>>();
}
return generatedDocuments.size() == 1 ? generatedDocuments.get(0) : asDocument("$and", generatedDocuments);
} else if (op == Ops.NOT) {
// Handle the not's child
Operation<?> subOperation = (Operation<?>) expr.getArg(0);
Operator subOp = subOperation.getOperator();
if (subOp == Ops.IN) {
return visit(ExpressionUtils.operation(Boolean.class, Ops.NOT_IN, subOperation.getArg(0), subOperation.getArg(1)), context);
} else {
Document arg = (Document) handle(expr.getArg(0));
return negate(arg);
}
} else if (op == Ops.OR) {
return asDocument("$or", collectConnectorArgs("$or", expr));
} else if (op == Ops.NE) {
Path<?> path = (Path<?>) expr.getArg(0);
Constant<?> constant = (Constant<?>) expr.getArg(1);
return asDocument(asDBKey(expr, 0), asDocument("$ne", convert(path, constant)));
} else if (op == Ops.STARTS_WITH) {
return asDocument(asDBKey(expr, 0), new BsonRegularExpression("^" + regexValue(expr, 1)));
} else if (op == Ops.STARTS_WITH_IC) {
return asDocument(asDBKey(expr, 0), new BsonRegularExpression("^" + regexValue(expr, 1), "i"));
} else if (op == Ops.ENDS_WITH) {
return asDocument(asDBKey(expr, 0), new BsonRegularExpression(regexValue(expr, 1) + "$"));
} else if (op == Ops.ENDS_WITH_IC) {
return asDocument(asDBKey(expr, 0), new BsonRegularExpression(regexValue(expr, 1) + "$", "i"));
} else if (op == Ops.EQ_IGNORE_CASE) {
return asDocument(asDBKey(expr, 0), new BsonRegularExpression("^" + regexValue(expr, 1) + "$", "i"));
} else if (op == Ops.STRING_CONTAINS) {
return asDocument(asDBKey(expr, 0), new BsonRegularExpression(".*" + regexValue(expr, 1) + ".*"));
} else if (op == Ops.STRING_CONTAINS_IC) {
return asDocument(asDBKey(expr, 0), new BsonRegularExpression(".*" + regexValue(expr, 1) + ".*", "i"));
} else if (op == Ops.MATCHES) {
return asDocument(asDBKey(expr, 0), new BsonRegularExpression(asDBValue(expr, 1).toString()));
} else if (op == Ops.MATCHES_IC) {
return asDocument(asDBKey(expr, 0), new BsonRegularExpression(asDBValue(expr, 1).toString(), "i"));
} else if (op == Ops.LIKE) {
String regex = ExpressionUtils.likeToRegex((Expression) expr.getArg(1)).toString();
return asDocument(asDBKey(expr, 0), new BsonRegularExpression(regex));
} else if (op == Ops.LIKE_IC) {
String regex = ExpressionUtils.likeToRegex((Expression) expr.getArg(1)).toString();
return asDocument(asDBKey(expr, 0), new BsonRegularExpression(regex, "i"));
} else if (op == Ops.BETWEEN) {
Document value = new Document("$gte", asDBValue(expr, 1));
value.append("$lte", asDBValue(expr, 2));
return asDocument(asDBKey(expr, 0), value);
} else if (op == Ops.IN) {
int constIndex = 0;
int exprIndex = 1;
if (expr.getArg(1) instanceof Constant<?>) {
constIndex = 1;
exprIndex = 0;
}
if (Collection.class.isAssignableFrom(expr.getArg(constIndex).getType())) {
// guarded by previous check
@SuppressWarnings("unchecked") Collection<?> values = ((Constant<? extends Collection<?>>) expr.getArg(constIndex)).getConstant();
return asDocument(asDBKey(expr, exprIndex), asDocument("$in", values));
} else {
Path<?> path = (Path<?>) expr.getArg(exprIndex);
Constant<?> constant = (Constant<?>) expr.getArg(constIndex);
return asDocument(asDBKey(expr, exprIndex), convert(path, constant));
}
} else if (op == Ops.NOT_IN) {
int constIndex = 0;
int exprIndex = 1;
if (expr.getArg(1) instanceof Constant<?>) {
constIndex = 1;
exprIndex = 0;
}
if (Collection.class.isAssignableFrom(expr.getArg(constIndex).getType())) {
// guarded by previous check
@SuppressWarnings("unchecked") Collection<?> values = ((Constant<? extends Collection<?>>) expr.getArg(constIndex)).getConstant();
return asDocument(asDBKey(expr, exprIndex), asDocument("$nin", values));
} else {
Path<?> path = (Path<?>) expr.getArg(exprIndex);
Constant<?> constant = (Constant<?>) expr.getArg(constIndex);
return asDocument(asDBKey(expr, exprIndex), asDocument("$ne", convert(path, constant)));
}
} else if (op == Ops.COL_IS_EMPTY) {
List<Object> list = new ArrayList<Object>(2);
list.add(asDocument(asDBKey(expr, 0), new ArrayList<Object>()));
list.add(asDocument(asDBKey(expr, 0), asDocument("$exists", false)));
return asDocument("$or", list);
} else if (op == Ops.LT) {
return asDocument(asDBKey(expr, 0), asDocument("$lt", asDBValue(expr, 1)));
} else if (op == Ops.GT) {
return asDocument(asDBKey(expr, 0), asDocument("$gt", asDBValue(expr, 1)));
} else if (op == Ops.LOE) {
return asDocument(asDBKey(expr, 0), asDocument("$lte", asDBValue(expr, 1)));
} else if (op == Ops.GOE) {
return asDocument(asDBKey(expr, 0), asDocument("$gte", asDBValue(expr, 1)));
} else if (op == Ops.IS_NULL) {
return asDocument(asDBKey(expr, 0), asDocument("$exists", false));
} else if (op == Ops.IS_NOT_NULL) {
return asDocument(asDBKey(expr, 0), asDocument("$exists", true));
} else if (op == Ops.CONTAINS_KEY) {
Path<?> path = (Path<?>) expr.getArg(0);
Expression<?> key = expr.getArg(1);
return asDocument(visit(path, context) + "." + key.toString(), asDocument("$exists", true));
} else if (op == MongodbOps.NEAR) {
return asDocument(asDBKey(expr, 0), asDocument("$near", asDBValue(expr, 1)));
} else if (op == MongodbOps.NEAR_SPHERE) {
return asDocument(asDBKey(expr, 0), asDocument("$nearSphere", asDBValue(expr, 1)));
} else if (op == MongodbOps.ELEM_MATCH) {
return asDocument(asDBKey(expr, 0), asDocument("$elemMatch", asDBValue(expr, 1)));
} else if (op == MongodbOps.NO_MATCH) {
return new Document("$where", new BsonJavaScript("function() { return false }"));
}
throw new UnsupportedOperationException("Illegal operation " + expr);
}
use of org.bson.BsonJavaScript in project pinpoint by naver.
the class WritecontextTest method parseBsonArrayWithValues.
@Test
public void parseBsonArrayWithValues() throws IOException {
BsonValue a = new BsonString("stest");
BsonValue b = new BsonDouble(111);
BsonValue c = new BsonBoolean(true);
BsonDocument document = new BsonDocument().append("int32", new BsonInt32(12)).append("int64", new BsonInt64(77L)).append("bo\"olean", new BsonBoolean(true)).append("date", new BsonDateTime(new Date().getTime())).append("double", new BsonDouble(12.3)).append("string", new BsonString("pinpoint")).append("objectId", new BsonObjectId(new ObjectId())).append("code", new BsonJavaScript("int i = 10;")).append("codeWithScope", new BsonJavaScriptWithScope("int x = y", new BsonDocument("y", new BsonInt32(1)))).append("regex", new BsonRegularExpression("^test.*regex.*xyz$", "big")).append("symbol", new BsonSymbol("wow")).append("timestamp", new BsonTimestamp(0x12345678, 5)).append("undefined", new BsonUndefined()).append("binary1", new BsonBinary(new byte[] { (byte) 0xe0, 0x4f, (byte) 0xd0, 0x20 })).append("oldBinary", new BsonBinary(BsonBinarySubType.OLD_BINARY, new byte[] { 1, 1, 1, 1, 1 })).append("arrayInt", new BsonArray(Arrays.asList(a, b, c, new BsonInt32(7)))).append("document", new BsonDocument("a", new BsonInt32(77))).append("dbPointer", new BsonDbPointer("db.coll", new ObjectId())).append("null", new BsonNull()).append("decimal128", new BsonDecimal128(new Decimal128(55)));
BasicDBObject query = new BasicDBObject();
query.put("ComplexBson", document);
logger.debug("document:{}", document);
NormalizedBson stringStringValue = MongoUtil.parseBson(new Object[] { query }, true);
logger.debug("val:{}", stringStringValue);
List list = objectMapper.readValue("[" + stringStringValue.getNormalizedBson() + "]", List.class);
Assert.assertEquals(list.size(), 1);
Map<String, ?> query1Map = (Map<String, ?>) list.get(0);
checkValue(query1Map);
}
use of org.bson.BsonJavaScript in project mongo-java-driver by mongodb.
the class MapReducePublisherImplTest method shouldBuildTheExpectedMapReduceToCollectionOperation.
@DisplayName("Should build the expected MapReduceToCollectionOperation")
@Test
void shouldBuildTheExpectedMapReduceToCollectionOperation() {
MapReduceStatistics stats = Mockito.mock(MapReduceStatistics.class);
TestOperationExecutor executor = createOperationExecutor(asList(stats, stats));
com.mongodb.reactivestreams.client.MapReducePublisher<Document> publisher = new MapReducePublisherImpl<>(null, createMongoOperationPublisher(executor), MAP_FUNCTION, REDUCE_FUNCTION).collectionName(NAMESPACE.getCollectionName());
MapReduceToCollectionOperation expectedOperation = new MapReduceToCollectionOperation(NAMESPACE, new BsonJavaScript(MAP_FUNCTION), new BsonJavaScript(REDUCE_FUNCTION), NAMESPACE.getCollectionName(), WriteConcern.ACKNOWLEDGED).verbose(true);
// default input should be as expected
Flux.from(publisher.toCollection()).blockFirst();
assertOperationIsTheSameAs(expectedOperation, executor.getWriteOperation());
// Should apply settings
publisher.batchSize(100).bypassDocumentValidation(true).collation(COLLATION).filter(new Document("filter", 1)).finalizeFunction(FINALIZE_FUNCTION).limit(999).maxTime(10, SECONDS).scope(new Document("scope", 1)).sort(Sorts.ascending("sort")).verbose(false);
expectedOperation.collation(COLLATION).bypassDocumentValidation(true).filter(BsonDocument.parse("{filter: 1}")).finalizeFunction(new BsonJavaScript(FINALIZE_FUNCTION)).limit(999).maxTime(10, SECONDS).maxTime(10, SECONDS).scope(new BsonDocument("scope", new BsonInt32(1))).sort(new BsonDocument("sort", new BsonInt32(1))).verbose(false);
Flux.from(publisher.toCollection()).blockFirst();
assertOperationIsTheSameAs(expectedOperation, executor.getWriteOperation());
}
use of org.bson.BsonJavaScript in project mongo-java-driver by mongodb.
the class MapReduceIterableImpl method execute.
MongoIterable<TResult> execute() {
if (inline) {
MapReduceWithInlineResultsOperation<TResult> operation = new MapReduceWithInlineResultsOperation<TResult>(namespace, new BsonJavaScript(mapFunction), new BsonJavaScript(reduceFunction), codecRegistry.get(resultClass)).filter(toBsonDocument(filter)).limit(limit).maxTime(maxTimeMS, MILLISECONDS).jsMode(jsMode).scope(toBsonDocument(scope)).sort(toBsonDocument(sort)).verbose(verbose).readConcern(readConcern).collation(collation);
if (finalizeFunction != null) {
operation.finalizeFunction(new BsonJavaScript(finalizeFunction));
}
return new OperationIterable<TResult>(operation, readPreference, executor);
} else {
MapReduceToCollectionOperation operation = createMapReduceToCollectionOperation();
String dbName = databaseName != null ? databaseName : namespace.getDatabaseName();
MongoIterable<TResult> delegated = new FindIterableImpl<TDocument, TResult>(new MongoNamespace(dbName, collectionName), documentClass, resultClass, codecRegistry, primary(), readConcern, executor, new BsonDocument(), new FindOptions().collation(collation)).batchSize(batchSize);
return new AwaitingWriteOperationIterable<TResult, MapReduceStatistics>(operation, executor, delegated);
}
}
Aggregations