我想使用 spring 框架 java API 在 mongo db 中运行不同的查询。查询是这样的:
db.location.distinct("state");
如何为上述创建查询对象。下面是一个糟糕的尝试。
import org.springframework.data.mongodb.core.query.Query;
public List<Location> getLocations(int skipCount, int pageSize)
{
Query query = new Query(Criteria.where("state").is("distinct);
return mongoOperations.find(query, Location.class);
/*
Don't want to do the below, as using Mao Pattern --
DBCollection collection = db.getCollection("location");
DBObject o1 = new BasicDBObject();
List list = collection.distinct("state", o1);
return list;
*/
}
最佳答案
实际上,MongoOperations 上并没有直接的 .distinct()
方法,也没有任何真正可以转换为方法的方法(除了聚合框架)。
但是您可以直接从底层 Collection 对象中获取方法:
List states = mongoOperations.getCollection("location").distinct("state");
当然需要提供集合名称,因为 .getCollection()
中的 Collection 对象来自底层 Java 驱动程序。
或者,如果您愿意,可以直接运行“命令”表单,但仍然需要为集合命名:
BasicDBObject distinctCommand = new BasicDBObject("distinct", "location")
.append("key", "state");
List states = (List)mongoOperation.executeCommand(distinctCommand).get("values");
关于java - 使用 Java 映射访问模式在 Mongo 中进行不同查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32265791/