我正在Spring应用程序中使用mongodb进行以下搜索:
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
private CampaignEntity incrByWithConversionRate(ObjectId campaignId, String key) {
Query query = new Query();
query.addCriteria(Criteria.where("id").is(campaignId));
Update update = new Update();
update.inc(key);
update.set("conversionRate", new Document("$divide", Arrays.asList("$clicks", "$views")));
return mongoTemplate.findAndModify(
query, update,
new FindAndModifyOptions().returnNew(true), CampaignEntity.class);
}
问题是它失败并出现以下错误:
org.springframework.data.mapping.MappingException: Expected to read Document Document{{$divide=[$clicks, $views]}} into type class java.lang.Float but didn't find a PersistentEntity for the latter!
注:CampaignEntity类定义如下:
@Data
@Document(collection = "campaigns")
public abstract class CampaignEntity extends BaseEntity {
private Integer clicks = 0;
private Integer views = 0;
private Float conversionRate;
}
1条答案
按热度按时间lsmepo6l1#
我最终使用了以下解决方案:
注意:CustomAggregationOperation类来自this SO answer。