Search in sources :

Example 1 with BsonJavaScript

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;
}
Also used : BsonJavaScript(org.bson.BsonJavaScript) GroupOperation(com.mongodb.operation.GroupOperation)

Example 2 with BsonJavaScript

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);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ArrayList(java.util.ArrayList) Document(org.bson.Document) BsonRegularExpression(org.bson.BsonRegularExpression) BsonJavaScript(org.bson.BsonJavaScript) BsonRegularExpression(org.bson.BsonRegularExpression) Collection(java.util.Collection) Map(java.util.Map)

Example 3 with BsonJavaScript

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);
}
Also used : BsonString(org.bson.BsonString) BsonBoolean(org.bson.BsonBoolean) BasicDBObject(com.mongodb.BasicDBObject) BsonInt32(org.bson.BsonInt32) BsonDecimal128(org.bson.BsonDecimal128) BsonDouble(org.bson.BsonDouble) ArrayList(java.util.ArrayList) List(java.util.List) BsonJavaScriptWithScope(org.bson.BsonJavaScriptWithScope) BsonNull(org.bson.BsonNull) BsonObjectId(org.bson.BsonObjectId) ObjectId(org.bson.types.ObjectId) BsonBinary(org.bson.BsonBinary) BsonDbPointer(org.bson.BsonDbPointer) Decimal128(org.bson.types.Decimal128) BsonDecimal128(org.bson.BsonDecimal128) BsonRegularExpression(org.bson.BsonRegularExpression) BsonObjectId(org.bson.BsonObjectId) BsonJavaScript(org.bson.BsonJavaScript) Date(java.util.Date) BsonTimestamp(org.bson.BsonTimestamp) BsonInt64(org.bson.BsonInt64) BsonSymbol(org.bson.BsonSymbol) BsonDocument(org.bson.BsonDocument) BsonDateTime(org.bson.BsonDateTime) BsonString(org.bson.BsonString) BsonArray(org.bson.BsonArray) Map(java.util.Map) BsonUndefined(org.bson.BsonUndefined) BsonValue(org.bson.BsonValue) Test(org.junit.Test)

Example 4 with BsonJavaScript

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());
}
Also used : BsonInt32(org.bson.BsonInt32) MapReduceStatistics(com.mongodb.internal.operation.MapReduceStatistics) BsonDocument(org.bson.BsonDocument) Document(org.bson.Document) BsonDocument(org.bson.BsonDocument) MapReduceToCollectionOperation(com.mongodb.internal.operation.MapReduceToCollectionOperation) BsonJavaScript(org.bson.BsonJavaScript) Test(org.junit.jupiter.api.Test) DisplayName(org.junit.jupiter.api.DisplayName)

Example 5 with BsonJavaScript

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);
    }
}
Also used : FindOptions(com.mongodb.client.model.FindOptions) MongoNamespace(com.mongodb.MongoNamespace) BsonJavaScript(org.bson.BsonJavaScript) MapReduceToCollectionOperation(com.mongodb.operation.MapReduceToCollectionOperation) BsonDocument(org.bson.BsonDocument)

Aggregations

BsonJavaScript (org.bson.BsonJavaScript)10 BsonDocument (org.bson.BsonDocument)6 BsonInt32 (org.bson.BsonInt32)4 Document (org.bson.Document)4 BsonRegularExpression (org.bson.BsonRegularExpression)3 BsonString (org.bson.BsonString)3 FindOptions (com.mongodb.client.model.FindOptions)2 MapReduceStatistics (com.mongodb.internal.operation.MapReduceStatistics)2 MapReduceToCollectionOperation (com.mongodb.internal.operation.MapReduceToCollectionOperation)2 ArrayList (java.util.ArrayList)2 Date (java.util.Date)2 Map (java.util.Map)2 BsonArray (org.bson.BsonArray)2 BsonBinary (org.bson.BsonBinary)2 BsonBoolean (org.bson.BsonBoolean)2 BsonDateTime (org.bson.BsonDateTime)2 BsonDbPointer (org.bson.BsonDbPointer)2 BsonDouble (org.bson.BsonDouble)2 BsonInt64 (org.bson.BsonInt64)2 BsonJavaScriptWithScope (org.bson.BsonJavaScriptWithScope)2