【问题标题】:Distinct Query in Mongo using Java Mao Access PatternMongo 中使用 Java Mao 访问模式的不同查询
【发布时间】:2015-11-22 19:19:02
【问题描述】:

我想使用 spring 框架 java API 在 mongo db 中运行不同的查询。查询是这样的:

db.location.distinct("state");

如何为上述创建 Query 对象。下面是一个糟糕的尝试。

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;
       */
}

【问题讨论】:

    标签: java spring mongodb spring-mongo


    【解决方案1】:

    实际上并没有直接在 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");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-23
      • 1970-01-01
      • 2017-06-10
      相关资源
      最近更新 更多