gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:39:00 25 4
gpt4 key购买 nike

如何仅使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com