jav*_*ude 17 mongodb spring-data
有没有人试图distinct在他们的查询中使用Spring Data for Mongo.如果你有一个例子,请发表它.我应该在哪里以及如何包括distinct flag?
链接到Spring Data Mongo示例 -Example 4.4. Query creation from method names
// Enables the distinct flag for the query
List<Person> findDistinctPeopleByLastnameOrFirstname(String lastname, String firstname);
List<Person> findPeopleDistinctByLastnameOrFirstname(String lastname, String firstname);
Run Code Online (Sandbox Code Playgroud)
小智 27
经过一番探索之后,我提出了以下解决方案,这是好的并且有效,但可以改进.我对Spring很新,所以如果你有更好的想法,请告诉我.
无论如何,这里是:
首先,我们使用@Autowired注释从spring-data-mongodb引入基础MongoTemplate
@Autowired
MongoTemplate mongoTemplate;
Run Code Online (Sandbox Code Playgroud)
一旦我们拥有了它,我们就可以用它来进行一些查询.请注意,这是稍微有点臭的部分,因为你必须告诉Spring返回类型是什么,它不是真的那样......
// Get the distinct stuff from MongoDB
List<String> coll = mongoTemplate.getCollection("mycollection").distinct("myfield");
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,您会注意到我已经定义了一个名为coll的List类型变量,它使用@Autowired MongoTemplate变量来获取集合,然后使用distinct来获取字段.这类似于db.whatever.distinct("term")Mongo shell.
小智 11
我的环境:spring-data-mongodb 2.0.5,jdk1.8,
这是我的代码示例:
import com.mongodb.client.DistinctIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
public List<String> queryAllCategory() {
List<String> categoryList = new ArrayList<>();
MongoCollection mongoCollection = mongoTemplate.getCollection("lexicon");
DistinctIterable distinctIterable = mongoCollection.distinct("category",String.class);
MongoCursor cursor = distinctIterable.iterator();
while (cursor.hasNext()) {
String category = (String)cursor.next();
categoryList.add(category);
}
return categoryList;
}
Run Code Online (Sandbox Code Playgroud)
关于不同的方法,请阅读:http : //mongodb.github.io/mongo-java-driver/3.7/javadoc/com/mongodb/client/MongoCollection.html#distinct-java.lang.String-java.lang.Class ——
Way to Retrieve strongly typed distinct values using Mongo Template:
mongoTemplate.query(Person.class)
.distinct("lastname")
.as(String.class)
.all();
Run Code Online (Sandbox Code Playgroud)
Here is the official documentation - https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongo-template.query.distinct
目前MongoDB不支持以独特的方式检索文档。它仅支持使用distinct命令返回不同的字段值。
由于您显然正在寻找后者,坏消息是,我们目前不支持派生查询中的任何预测。有关这方面的进展,请关注相关的 JIRA票证。
自从发布这个问题以来,很多事情都发生了变化。回答我自己的问题,因为这个问题不断出现。
从那时起就有支持,3.0而且更高
public DistinctIterable<String> getUniqueTask() {
return mongoTemplate.getCollection(TABLE).distinct("FIELD", String.class);
}
Run Code Online (Sandbox Code Playgroud)
旁注:您甚至可以向此查询添加过滤器/正则表达式。阅读文档。如果找不到,ping,将发布答案。
| 归档时间: |
|
| 查看次数: |
23272 次 |
| 最近记录: |