Executing Mongo like Query (JSON)through Java

后端 未结 5 1608
执笔经年
执笔经年 2020-12-25 14:54

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

5条回答
  •  北海茫月
    2020-12-25 15:28

    Yes, there is way, by passing the filter as a string. Example:

    BasicDBObject query = BasicDBObject.parse("{userId: {$gt: \"1\"}}");
    FindIterable dumps = crapCollection.find(query);
    

    You can Also use com.mongodb.util.JSON, but I don't recommend it. It's less descriptive.

    DBObject dbObject = (DBObject)JSON.parse("{userId: {$gt: \"1\"}}");
    

    Please notice that this might be vulnerable to SQL injections because you parse/build the filter yourself.

    I recommend using Jongo's parameterized query.

提交回复
热议问题