1
votes

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

1 Answers

0
votes

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);
}