Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MongoDB Java驱动程序:如何从Java驱动程序插入到任何集合中_Java_Mongodb_Jongo - Fatal编程技术网

MongoDB Java驱动程序:如何从Java驱动程序插入到任何集合中

MongoDB Java驱动程序:如何从Java驱动程序插入到任何集合中,java,mongodb,jongo,Java,Mongodb,Jongo,我有一个面向客户端的应用程序,它的函数将2个参数作为字符串,arg1是集合,arg2是函数,arg2是对象的哈希 所以在Java中我有 foo(String collection, String object): /*我的db对象来自mongoDB驱动程序 我要插入的集合是“用户”*/ 现在我遇到了麻烦 db.runCommand({insert : collection (? can i do this), ????}) <- I dont know ho

我有一个面向客户端的应用程序,它的函数将2个参数作为字符串,arg1是集合,arg2是函数,arg2是对象的哈希

所以在Java中我有

foo(String collection, String object):
/*我的db对象来自mongoDB驱动程序 我要插入的集合是“用户”*/

现在我遇到了麻烦

db.runCommand({insert : collection (? can i do this),
               ????}) <- I dont know how to right this and append the object
db.runCommand({insert:collection(?我可以这样做吗),
?})样本:

DBCollection coll = db.getCollection("collection");

/* {
   "name" : "MongoDB",
   "type" : "database",
   "count" : 1,
   "info" : {
               x : 203,
               y : 102
             }
} */

BasicDBObject doc = new BasicDBObject("name", "MongoDB").
                              append("type", "database").
                              append("count", 1).
                              append("info", new BasicDBObject("x", 203).append("y", 102));

coll.insert(doc);

听起来就像是在尝试编写自己的驱动程序——找出用户想要执行的命令,然后将其转换为BSON发送到MongoDB,这正是MongoDB Java驱动程序所做的

您可以使用Java驱动程序运行任意命令,使用
db.command(…)
。您必须创建一个表示要运行的命令的DBObject

关于您的评论“我发现的示例已经有一个预定义的集合,但我需要对其进行抽象。”,@mert是正确的,因为您可以使用以下方法获得所需的集合:

DBCollection coll = db.getCollection(collection);
其中,
collection
是在
foo
方法中声明的字符串变量


但是,我不确定您希望提供的功能的安全性-您基本上提供了一个工具,允许用户对您的数据库运行任何任意命令,尽管MongoDB是一个NoSQL数据库,但这样打开它会暴露类似的漏洞,以防攻击。您的用例是什么?你真的想绕过并重新发明驱动程序,让你的用户在数据库上做任何他们想做的事情吗?驱动程序是使用严格的API编写的,原因有两个:1)帮助开发人员;2)防止人们对数据库做不正确或令人讨厌的事情。

文档结构部分应该在注释中吗?因为如果你将代码复制到一个类中,它就不会编译。@mert我的意思是,如果你不知道用户是要传入collection.insert()还是collection.find()或collection.insert().find().aggregate()等等。如果你连什么收藏都不知道呢?有没有一种方法可以模拟原始mongoDB,而不用自己进行映射?非常感谢。
DBCollection coll = db.getCollection(collection);