如果您的问题是:
我可以将上面的字符串传递给Java驱动程序并让驱动程序执行它吗?
那么您可以使用db.eval 命令。例如:
MongoDatabase database = mongoClient.getDatabase("...");
Bson command = new Document("eval", "db.orders.aggregate([\n" +
" {\n" +
" $unwind: \"$specs\"\n" +
" },\n" +
" {\n" +
" $lookup:\n" +
" {\n" +
" from: \"inventory\",\n" +
" localField: \"specs\",\n" +
" foreignField: \"size\",\n" +
" as: \"inventory_docs\"\n" +
" }\n" +
" },\n" +
" {\n" +
" $match: { \"inventory_docs\": { $ne: [] } }\n" +
" }\n" +
"])");
Document result = database.runCommand(command);
但是 ... db.eval 命令已被弃用,其用法为 is not advised。 MongoDB Java 驱动程序可用于执行聚合,但不能以“字符串形式”执行,而是使用 Java 驱动程序的聚合助手来创建聚合命令的 Java 形式。关于这个in the docs的大量细节。
这是一个使用 3.x MongoDB Java 驱动程序的(未经测试的)示例...
MongoCollection<Document> collection = mongoClient.getDatabase("...").getCollection("...");
AggregateIterable<Document> documents = collection.aggregate(Arrays.asList(
// the unwind stage
new Document("$unwind", "$specs"),
// the lookup stage
new Document("$lookup", new Document("from", "inventory")
.append("localField", "specs")
.append("foreignField", "size")
.append("as", "inventory_docs")),
// the match stage
new Document("$match", new Document("inventory_docs", new BasicDBObject("$ne", new String[0])))
));
.. 这可能有助于您了解从 shell 脚本到 Java 的转换形式。