猿问

在 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() 怎么办?


海绵宝宝撒
浏览 252回答 3
3回答

UYOU

寻找:db.runCommand({&nbsp; &nbsp; find: "mycol",&nbsp; &nbsp; filter: { by: "tutorials point"}})插入:db.runCommand({&nbsp; &nbsp; insert: "mycol",&nbsp; &nbsp; documents: [ { _id: 1, foo: "bar"} ]})我认为在 java 中这样做最简单的原因是使用 Jongo ( http://jongo.org/ )。语法与 mongo shell 非常相似。jongo.runCommand("{find: 'mycol', filter: { by: 'tutorials point'}}")

慕尼黑8549860

举例说明它是如何工作的这是我的查询db.getCollection('Collection').aggregate([{&nbsp; &nbsp; $unwind: '$somearray'}, {&nbsp; &nbsp; $match: {&nbsp; &nbsp; &nbsp; &nbsp; _id: ObjectId("123456"),&nbsp; &nbsp; &nbsp; &nbsp; 'somearray.type': "blabla"&nbsp; &nbsp; }}, {&nbsp; &nbsp; $project: {&nbsp; &nbsp; &nbsp; &nbsp; '_id':0,&nbsp; &nbsp; &nbsp; &nbsp; 'name': '$somearray.name',&nbsp; &nbsp; &nbsp; &nbsp; 'phone': '$phone'&nbsp; &nbsp; }}])这是我的 Java 程序,它和查询一样public MongoIterable < Document > GetList(String collectionName, String id) {&nbsp; &nbsp; MongoClient mongoClient = new MongoClient();&nbsp; &nbsp; MongoDatabase database = mongoClient.getDatabase("MyDB");&nbsp; &nbsp; MongoCollection < Document > collection = database.getCollection("collectionName");&nbsp; &nbsp; Document match = Document.parse("{_id: ObjectId('" + id + "'),'somearray.type': 'blabla'}");&nbsp; &nbsp; Document project = Document.parse("{ $project: { _id: 0,'name': '$somearray.name'},&nbsp; 'phone': '$phone'}");&nbsp; &nbsp; MongoIterable < Document > output = collection.aggregate(Arrays.asList(Aggregates.unwind("$somearray"), Aggregates.match(match), project));&nbsp; &nbsp; return output;}

噜噜哒

你不能这样做。首先你需要得到你的collection喜欢 :MongoCollection<Document> collection = database.getCollection("test");拥有后,collection您可以使用 util 运行原始查询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);
随时随地看视频慕课网APP

相关分类

Java
我要回答