Java中的命令行查询

编程入门 行业动态 更新时间:2024-10-25 20:28:43
本文介绍了Java中的命令行查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在访问MongoDB,并希望在Java中重用典型的命令行查询。 我知道可以使用BasicDBObject,但我想使用这样的命令行查询:

I'm accessing a MongoDB and want to reuse typical command line queries also within Java. I know it is possible to use the BasicDBObject, but I want to use command line queries like this:

db.MyCollection.find()

我现在尝试使用数据库的command()方法:

I tried now using the command() method of the database:

MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.getDB("MyDatabase"); CommandResult result= dbmand("db.MyCollection.find()"); JSONObject resultJson = new JSONObject(result.toString()); System.out.println(resultJson.toString(4));

但这会返回以下结果。

But this returns me the following result.

"ok": 0, "code": 59, "errmsg": "no such cmd: db.MyCollection.find()", "bad cmd": {"db.MyCollection.find()": true}, "serverUsed": "localhost:27017"

如何在Java中运行命令行查询?

我不想使用DBCollection类 - 因为它不再可能为不同的集合运行查询。

I do not want to use the DBCollection class - because then it's not anymore possible to run queries for different collections.

DBCollection collection = db.getCollection("MyCollection"); collection.find(); //NOT THIS

推荐答案

我认为你不能去做。使用 dbmand(),您只能使用这些命令。也许你可以得到这样的东西(我遇到了预期结果的问题)

I don't think you can do that. With dbmand() you are limited to these commands. Maybe you could get something like this to work (I'm having problems with getting expected results)

final DBObject command = new BasicDBObject(); command.put("eval", "function() { return db." + collectionName + ".find(); }"); CommandResult result = dbmand(command);

BTW,你为什么不使用像 db.getCollection这样的链式调用( collectionName)。find(); 以避免粘贴到一个集合?

BTW, why don't you use chained calls like db.getCollection(collectionName).find(); to avoid sticking to one collection?

更多推荐

Java中的命令行查询

本文发布于:2023-10-23 00:17:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519174.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:命令行   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!