json字符串的Spring数据mongodb查询

Moh*_*bin 9 java mongodb spring-data-mongodb

我的代码需要支持客户端发送的任何查询.客户端将以json的形式发送查询.我使用java mongo驱动程序低级api使用以下代码完成此操作,
BasicDBObject queryObject = (BasicDBObject) JSON.parse(whereJson.toString());
因为我是spring数据mongodb中的新手,我无法在Query或Criteria类中找到类似的解决方案.我检查了不同的教程,但找不到任何教程.有可能在spring数据mongodb中做或者我应该使用低级apis本身吗?

chr*_*dam 12

您可以使用BasicQuery对象从普通JSON字符串创建Query实例.以下示例演示了如何从普通JSON字符串构造Query实例:

BasicQuery query = new BasicQuery("{ age : { $lt : 50 } }");
List<Person> result = mongoTemplate.find(query, Person.class);    
Run Code Online (Sandbox Code Playgroud)

另一种使用低级API的方法:

DBObject dbObject = (DBObject) JSON.parse(query); 
DBCursor cursor = mongoTemplate.getCollection("person").find(dbObject); 
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用MongoConverter read()方法将返回对象映射回Person POJO:

List<Person> returnList = new ArrayList<Person>();
while (cursor.hasNext()) { 
    DBObject obj = cursor.next(); 
    Person person = mongoTemplate.getConverter().read(Person.class, obj);  
    returnList.add(person); 
} 
Run Code Online (Sandbox Code Playgroud)

  • 哇.谢谢你.我被困住了,等待解决方案.非常感谢 :) (2认同)
  • @Mohammedshebin 不用担心,很乐意提供帮助:) (2认同)