json - 如何仅使用 mongo-java-driver 执行 MongoDB native 查询(JSON)?

标签 json mongodb native mongo-java-driver

如何仅使用 java-mongo-driver 触发 mongo 原生查询。

No Spring-Data or EclipseLink or Hibernate OGM, Only using java-mongo-driver

示例查询:

db.orders.aggregate([
   {
      $unwind: "$specs"
   },
   {
      $lookup:
         {
            from: "inventory",
            localField: "specs",
            foreignField: "size",
            as: "inventory_docs"
        }
   },
   {
      $match: { "inventory_docs": { $ne: [] } }
   }
])

最佳答案

如果您的问题是:

Can I pass the above string into the Java driver and have the driver execute it?

然后你可以使用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 的转换形式。

关于json - 如何仅使用 mongo-java-driver 执行 MongoDB native 查询(JSON)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47093563/

相关文章:

python - 如何在 Python 中有效地解析大型 JSON 文件?

java - ReSTLet 将 JSON 转换为 LinkedHashMap 而不是 List<MyObject>?

mongodb - 如何在 mongodb 中查询过去六个月的日期

php - 如何强制 PHP Mongo 驱动程序将结果作为对象而不是数组返回

python - 在 Python 中将 Json 转换为 Excel 或 CSV

json - jq 按键值排序

node.js - 在 mongoose 中查找相对于我的坐标在 10 英里半径内的附近用户

c++ - 如何使用 Visual Studio 2017 调试从 asp.net 调用的 native C++

c++ - 如何使用主 C++ 程序构建声音相关库(不使用任何第三方库)

visual-studio-2012 - 这些类型的 VS2012 命令提示符是什么?