通过Java执行像Query(JSON)这样的Mongo [英] Executing Mongo like Query (JSON)through Java

查看:412
本文介绍了通过Java执行像Query(JSON)这样的Mongo的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有办法直接通过Java执行类似查询的mongo,即我们将mongoDB查询作为字符串提供给Java驱动程序中的函数,用于mongoDB作为String对象并返回DBCursor对象。类似于:

I was wondering if there is a way to execute mongo like query directly through Java i.e. we give mongoDB like query as a String to a function in Java driver for mongoDB as a String Object and an DBCursor Object is returned. Something like:

import com.mongodb.*;
import java.net.UnknownHostException;
public class ExecuteQuery {
public static void main(String args[]){
    try{
          Mongo m = new Mongo();
          DB db = m.getDB("test");
          DBCollection coll = db.getCollection("first");
          DBObject doc = new BasicDBObject();
          DBCursor cur =coll.executeQuery("db.first.find({"username":"joe"})");
       }
       catch(UnknownHostException e){
          System.out.println(e);
       }
       catch (MongoException.DuplicateKey e) {
          System.out.println("Exception Caught" + e);
       }
}
}

注意: executeQuery()不是内置函数。它仅用于演示目的。
那么,java api中是否有一个函数将json字符串转换为 BasicDBObject 实例?谢谢。

Note: executeQuery() is not a built in function. It is just used for demonstration purposes. So, Is there a function in the java api which converts a json string to a BasicDBObject instance? Thanks.

推荐答案

你在这里展示的不是JSON,它是嵌入式MongoDB Shell的Javascript代码。如果由于某种原因需要在Java环境中执行代码,则必须嵌入Javascript引擎(如 Rhino )并实现兼容的API。

What you showed here is not JSON, it's Javascript code for embedded MongoDB Shell. If you need for some reason to execute the code inside Java environment you will have to embed Javascript engine (like Rhino) and implement compatible API.

否则你只需要将JSON转换为 DBObject ,你就可以用 JSON.parse()方法或任何其他方法JSON映射库,如 Jackson 。请注意,MongoDB使用JSON中不存在的扩展数据类型集: http ://www.mongodb.org/display/DOCS/Data+Types+and+Conventions

Otherwise you just need to convert JSON to DBObject and you can do this with JSON.parse() method or any other JSON-mapping library like Jackson. Note that MongoDB uses extended set of data types that are not present in JSON: http://www.mongodb.org/display/DOCS/Data+Types+and+Conventions

UPD:Scott Hernandez指出 JSON.parse

UPD: Scott Hernandez pointed out about JSON.parse.

这篇关于通过Java执行像Query(JSON)这样的Mongo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆