Cha*_*shi 5 json native mongodb mongo-java-driver
如何仅使用 java-mongo-driver 触发 mongo 本机查询。
没有Spring-Data 或 EclipseLink 或 Hibernate OGM,仅使用java-mongo-driver
示例查询:
db.orders.aggregate([
{
$unwind: "$specs"
},
{
$lookup:
{
from: "inventory",
localField: "specs",
foreignField: "size",
as: "inventory_docs"
}
},
{
$match: { "inventory_docs": { $ne: [] } }
}
])
Run Code Online (Sandbox Code Playgroud)
如果你的问题是:
我可以将上面的字符串传递给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);
Run Code Online (Sandbox Code Playgroud)
但是...该db.eval命令已被弃用,并且不建议使用它。MongoDB Java 驱动程序可用于执行聚合,但不能以“字符串形式”执行聚合,而是使用 Java 驱动程序的聚合帮助程序来创建聚合命令的 Java 形式。文档中有很多关于此的详细信息。
这是一个使用 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])))
));
Run Code Online (Sandbox Code Playgroud)
..这可能会帮助您了解从 shell 脚本到 Java 的翻译形式。
| 归档时间: |
|
| 查看次数: |
8995 次 |
| 最近记录: |