首页 > 解决方案 > 在 java 中运行自定义 mongodb 查询

问题描述

我想使用接收 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":"教程点"})。

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

标签: javamongodbdatabase-connectionbson

解决方案


寻找:

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'}}")

推荐阅读