1

Is there any way to execute a mongo query or js script in the same format as in the mongo shell?

Sample query:

db.getCollection('MyCollection').aggregate([
    {
        "$unwind": "$rootElement.list"
    },
    {
        "$match": {$expr: {$eq: ["$rootElement.list.elementId", "$rootElement.elementId"]}}
    }
]

I want just to get this query as a string or as query.js file and execute from java code.

In version 4.2, MongoDB removes the eval command, but is there any alternative? Thx.

1 Answer 1

0

See the following code

BsonArray bsonValues = BsonArray.parse("script")

LinkedList<BsonDocument> documents = bsonValues.stream().map(x -> x.asDocument()).collect(Collectors.toCollection(LinkedList::new))

MongoCursor<Document> iterator = collection.aggregate(documents).iterator();

if(iterator.hasNext()){
    return IteratorUtils.toList(iterator);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.