使用 spring data mongo 驱动程序,我想使用一个查询更新 mongodb 中的多个文档,并且这些文档将具有不同的更新值。我尝试了以下代码,但对于与查询条件匹配的所有文档,它都会具有相同的更新值。
List<Criteria> bigCriteria = new ArrayList<Criteria>();
for (MyClass myClass : myClasses){
Criteria criteria = Criteria.where("_id").is(myClass.getId());
bigCriteria.add(criteria);
}
//next line is just a psedudo code to explain what I intend to do here
query = <<create an or query using bigCriteria created above>>;
Update update = new Update();
update.set("age":11);
mongoOperation.updateMulti(query, update, User.class);
Run Code Online (Sandbox Code Playgroud)
有没有办法用不同的值更新所有文档?
我有 2 个文档,主题和评论。每个主题都有很多评论,文档如下所示:
@Document
public class Topic {
@Id
private String id;
@Indexed(unique = true)
@NotBlank
private String title;
}
@Document
public class Comment {
@NotBlank
private String text;
@Indexed
@NotBlank
private String topic; // id of topic
@CreatedDate
@Indexed
private LocalDateTime createdDate;
}
Run Code Online (Sandbox Code Playgroud)
所以我实际上将 Topic 的 id 引用保存在评论中。
这是我的聚合场景:列出今天收到最多评论的主题。所以三件事:
这是到目前为止的代码:
MatchOperation filterCreatedDate = match(Criteria.where("createdDate").gte(today.atStartOfDay()).lt(today.plusDays(1).atStartOfDay()));
GroupOperation groupByTopic = group("topic").count().as("todaysCommentsCount");
SortOperation sortByTodaysCommentsCount = sort(Sort.Direction.DESC, "todaysCommentsCount");
Aggregation aggregation = newAggregation(filterCreatedDate, groupByTopic, sortByTodaysCommentsCount);
AggregationResults<TopTopic> result = mongoTemplate.aggregate(aggregation, …Run Code Online (Sandbox Code Playgroud) 我正在使用 Spring Boot(V2.2.2.RELEASE) + Spring Data Mongo 示例。在这个例子中,我有如下记录
{
"_id" : ObjectId("5cb825e566135255e0bf38a4"),
"firstName" : "John",
"lastName": "Doe"
}
Run Code Online (Sandbox Code Playgroud)
我的存储库
@Repository
public interface EmployeeRepository extends CrudRepository<Employee, ObjectId>{
Employee findById(String id);
}
Run Code Online (Sandbox Code Playgroud)
代码
Employee findById = employeeRepository.findById("5cb825e566135255e0bf38a4");
System.out.println(findById);
Run Code Online (Sandbox Code Playgroud)
即使下面的代码也不起作用
Query query = new Query(Criteria.where("id").is(new ObjectId("5cb825e566135255e0bf38a4")));
List<Employee> find = mongoTemplate.find(query, Employee.class);
Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个简单的应用程序,使用 MongoTemplate 处理 MongoDB 数据库。然而,这个方法:
@Bean
public MongoTemplate mongoTemplate() throws Exception {
MongoTemplate template = new MongoTemplate(mongoClient(), this.mongodbName);
return template;
}
Run Code Online (Sandbox Code Playgroud)
因以下异常而失败:
Error creating bean with name 'mongoTemplate' defined in class path resource [com/myapp/tryout/repository/config/MongoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is java.lang.NoSuchMethodError: 'java.lang.String com.mongodb.connection.ClusterSettings.getDescription()'
Run Code Online (Sandbox Code Playgroud)
pom.xml 具有以下依赖项:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.5</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
Spring版本是5.2.6。com.mongodb.connection.ClusterSettings 的文档表明该方法确实已被弃用。此外,通过查看 ClusterSettings 类,我找不到此方法。
我的问题是:是否与当前版本的 Spring 和 mongo-java-driver 不匹配有关?如果是,您能否指出要使用的正确包组合? …
我正在尝试升级到 spring-boot 2.3.6。我正在使用 spring-data MongoRepositories,没有直接调用 MongoClient 或 MongoClient。
获取异常:
Caused by: org.bson.codecs.configuration.CodecConfigurationException: The uuidRepresentation has not been specified, so the UUID cannot be encoded.
at org.bson.codecs.UuidCodec.encode(UuidCodec.java:72)
at org.bson.codecs.UuidCodec.encode(UuidCodec.java:37)
at org.bson.codecs.EncoderContext.encodeWithChildContext(EncoderContext.java:91)
at org.bson.codecs.DocumentCodec.writeValue(DocumentCodec.java:198)
at org.bson.codecs.DocumentCodec.writeMap(DocumentCodec.java:212)
at org.bson.codecs.DocumentCodec.encode(DocumentCodec.java:154)
at org.bson.codecs.DocumentCodec.encode(DocumentCodec.java:45)
Run Code Online (Sandbox Code Playgroud)
尝试过定制
Caused by: org.bson.codecs.configuration.CodecConfigurationException: The uuidRepresentation has not been specified, so the UUID cannot be encoded.
at org.bson.codecs.UuidCodec.encode(UuidCodec.java:72)
at org.bson.codecs.UuidCodec.encode(UuidCodec.java:37)
at org.bson.codecs.EncoderContext.encodeWithChildContext(EncoderContext.java:91)
at org.bson.codecs.DocumentCodec.writeValue(DocumentCodec.java:198)
at org.bson.codecs.DocumentCodec.writeMap(DocumentCodec.java:212)
at org.bson.codecs.DocumentCodec.encode(DocumentCodec.java:154)
at org.bson.codecs.DocumentCodec.encode(DocumentCodec.java:45)
Run Code Online (Sandbox Code Playgroud)
没有帮助,同样的例外。
在 spring-boot 2.3.6 中自定义 UUID 编解码器的正确方法是什么?
谢谢。
我需要动态创建一个标准,但我有问题,我如何动态建立标准.
我需要完全一样,这里建立动态查询与Spring数据MongoDB的标准,但同时,我为我的标准列表转换为指定者作为其一直在说,orCriteria不具备条件的支持[我得到一个错误]
到目前为止,这是我的努力
这是我的查询结构
{
"query":{
"where":[{
"or":[
{
"fieldName":"title","fieldValue":"Demo Event NEW YORK IIII22222",
"operator":"equal"
},
{
"fieldName":"createdBy","fieldValue":"system",
"operator":"equal"
}
]
}
]
}
}
Run Code Online (Sandbox Code Playgroud)
这是我解析它来创建标准
if(null != eventSearch.getQuery())
{
if(null != eventSearch.getQuery().getWhere() && eventSearch.getQuery().getWhere().size()> 0)
{
for (Where whereClause : eventSearch.getQuery().getWhere()) {
if(null != whereClause.getOr() && whereClause.getOr().size() > 0){
for (Field field: whereClause.getOr()) {
if(field.getOperator().equalsIgnoreCase(QueryOperator.IS))
{
// So i need to append an or Condition to main query for each or object in my query can anyone …Run Code Online (Sandbox Code Playgroud) 我正在使用spring boot 1.1.5构建一个MongoDb rest应用程序.我创建了一个存储库:
@RepositoryRestResource(collectionResourceRel = "SourceProductV1Repository", path = "SourceProductV1Repository")
public interface SourceProductV1Repository extends MongoRepository<SourceProductV1Model, String> {
public List<SourceProductV1Model> findByUser (@Param("user") MongoUser user);
}
Run Code Online (Sandbox Code Playgroud)
我定义了一个转换器将String转换为MongoUser(转换器在spring上下文中正确注册):
@Component
public class String2MongoUserConverter implements Converter<String, MongoUser>{
private static final Log LOGGER = LogFactory.getLog(String2MongoUserConverter.class.getName());
@Override
public MongoUser convert(String s) {
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
所以当我尝试访问时 http://localhost:8080/SourceProductV1Repository/search/findByUser?user=test
我收到以下错误:
org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type java.lang.String to type @org.springframework.data.repository.query.Param com.ddelizia.model.MongoUser
at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:291)
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:177)
at org.springframework.data.rest.core.invoke.ReflectionRepositoryInvoker.prepareParameters(ReflectionRepositoryInvoker.java:265)
at org.springframework.data.rest.core.invoke.ReflectionRepositoryInvoker.invokeQueryMethod(ReflectionRepositoryInvoker.java:230)
at org.springframework.data.rest.webmvc.RepositorySearchController.executeQueryMethod(RepositorySearchController.java:236)
at org.springframework.data.rest.webmvc.RepositorySearchController.executeSearch(RepositorySearchController.java:146)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native …Run Code Online (Sandbox Code Playgroud) 我已经从春季启动版本1.1.5升级到1.2.1,现在我得到了NoSuchBeanDefinitionException.
我有简单的主要课程
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Run Code Online (Sandbox Code Playgroud)
后来我有了回购
@Repository
public interface UserRepository extends MongoRepository<User, String>, UserRepositoryCustom {
...
}
Run Code Online (Sandbox Code Playgroud)
定制回购
public interface UserRepositoryCustom {
// custom methods
}
Run Code Online (Sandbox Code Playgroud)
和impl类.
在将spring boot版本更新到1.2.1之前,一切都按预期工作.我已阅读https://github.com/spring-projects/spring-boot/issues/2237并尝试删除@Repository注释但未成功.我错过了什么吗?Thnx寻求帮助
编辑堆栈跟踪:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.example.respositories.UserRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1308) …Run Code Online (Sandbox Code Playgroud) 怎么了,我试着在评论列表中添加新评论,评论被映射到Post类的列表.
这是我的代码.
Post.java
@Document
public class Post {
@Id
private String id;
@DBRef
private List<Comment> comments;
public void addComment(Comment comment) {
if (comments == null) {
comments = new ArrayList<>();
}
this.comments.add(comment);
}
// getters and setters....
}
Run Code Online (Sandbox Code Playgroud)
Comment.java
@Document
public class Comment {
@Id
private String id;
private String comment;
private int rating;
// getters and setters....
}
Run Code Online (Sandbox Code Playgroud)
的Test.class
@Test
public void savePostWithComments() {
Post post = postRepository.findAll().get(1);
Comment comment = new Comment();
comment.setComment("comment");
comment.setRating(5);
post.addComment(comment);
postRepository.save(post);
}
Run Code Online (Sandbox Code Playgroud)
测试因此错误而失败 …
我正在遍历键/值对的列表,并对每个键/值执行查找。我可以创建一个单一的查询文档以在sql中实现联合吗,这样就只有一个数据库调用。
List<User> userList = new ArrayList<User>();
for (Map accounts:attributes) {
Query query = new Query();
List<Criteria> andCriteriaList = new ArrayList<Criteria>();
accounts.forEach((key, value) -> {
Criteria criteria = Criteria.where((String) key).is(value);
andCriteriaList.add(criteria);
});
query.addCriteria(new Criteria().andOperator(andCriteriaList.toArray(new Criteria[andCriteriaList.size()])));
if (mongoTemplate.exists(query, User.class)) {
userList.add((User)mongoTemplate.find(query, User.class));
//System.out.println(mongoTemplate.find(query, User.class));
}
Run Code Online (Sandbox Code Playgroud)
谢谢,