[英]Running custom mongodb queries in java
我想使用接收 BSON 数据的 runCommand() 运行原始 mongoDb 查询。 以下是我的代码
MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("MyDB");
MongoCollection<Document> collection = (MongoCollection<Document>)database.runCommand(??);
如果我的查询是
db.mycol.find({"by":"tutorials point"}).
我必须在 runCommand() 中传递什么 BSON 数据? 难道只是
{{“by”:“教程点”}}
或者
db.mycol.find({"by":"tutorials point"}).
如果不是 find() 而不是我必须使用 Insert() 如何 go 关于它?
找:
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'}}")
你不能这样做。 首先,您需要获取collection
像: MongoCollection<Document> collection = database.getCollection("test");
有了collection
,就可以使用util import com.mongodb.util.JSON;
运行原始查询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);
举例说明它是如何工作的这是我的查询
db.getCollection('Collection').aggregate([{
$unwind: '$somearray'
}, {
$match: {
_id: ObjectId("123456"),
'somearray.type': "blabla"
}
}, {
$project: {
'_id':0,
'name': '$somearray.name',
'phone': '$phone'
}
}])
这是我的 Java 程序,它与查询相同
public MongoIterable < Document > GetList(String collectionName, String id) {
MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("MyDB");
MongoCollection < Document > collection = database.getCollection("collectionName");
Document match = Document.parse("{_id: ObjectId('" + id + "'),'somearray.type': 'blabla'}");
Document project = Document.parse("{ $project: { _id: 0,'name': '$somearray.name'}, 'phone': '$phone'}");
MongoIterable < Document > output = collection.aggregate(Arrays.asList(Aggregates.unwind("$somearray"), Aggregates.match(match), project));
return output;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.