【问题标题】:Running custom mongodb queries in java在 java 中运行自定义 mongodb 查询
【发布时间】:2019-07-28 02:28:58
【问题描述】:

我想使用接收 BSON 数据的 runCommand() 运行原始 mongoDb 查询。 以下是我的代码

    MongoClient mongoClient = new MongoClient();
    MongoDatabase database = mongoClient.getDatabase("MyDB");
    MongoCollection<Document> collection = (MongoCollection<Document>)database.runCommand(??);        

如果我的查询是

db.mycol.find({"by":"教程点"}).

我必须在 runCommand() 中传递的 BSON 数据应该是什么?难道只是

{{"by":"教程点"}}

db.mycol.find({"by":"教程点"}).

如果我必须使用 Insert() 而不是 find() 怎么办??

【问题讨论】:

    标签: java mongodb database-connection bson


    【解决方案1】:

    查找:

    db.runCommand({
        find: "mycol",
        filter: { by: "tutorials point"}
    })
    

    插入:

    db.runCommand({
        insert: "mycol",
        documents: [ { _id: 1, foo: "bar"} ]
    })
    

    我认为在 java 中这样做最简单的原因是使用 Jongo (http://jongo.org/)。 语法与 mongo shell 非常相似。

    jongo.runCommand("{find: 'mycol', filter: { by: 'tutorials point'}}")
    

    【讨论】:

      【解决方案2】:

      你不能那样做。 首先你需要得到你的collection

      点赞:MongoCollection&lt;Document&gt; collection = database.getCollection("test");

      拥有collection 后,您可以使用实用工具import com.mongodb.util.JSON; 运行原始查询

      这将是你想要做的一个例子:

      MongoClient mongoClient = new MongoClient();
      MongoDatabase database = mongoClient.getDatabase("MyDB");
      MongoCollection<Document> collection = database.getCollection("mycol");
      
      String rawQuery = "{\"by\": \"tutorials point\"}";
      
      DBObject query = (DBObject) JSON.parse(rawQuery);
      collection.find(query);
      

      【讨论】:

        猜你喜欢
        • 2021-08-16
        • 2017-11-06
        • 1970-01-01
        • 2019-07-07
        • 2020-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多