Mongodb 的 sql,文档 wallpaper 的 _id 关联文档 wallpaper_get_success 的 wallpaper_id 进行查询。
db.wallpaper.aggregate([
{
$addFields: {
"_id": {
"$toString": "$_id"
}
}
},
{
"$lookup": {
"from": "wallpaper_get_success",
"localField": "_id",
"foreignField": "wallpaper_id",
"as": "success_id"
}
},
{
"$match": {
"success_id": {
"$ne": []
}
}
},
{
"$sample": {
"size": 5
}
}
])
在MongoDB数据库进行 *** 作 sql是可以的,但是在Java中使用MongoTemplate就不行,在newAggregation 中进行 lookup,match,sample *** 作都可以,但是进行 addFields *** 作就不行。
Aggregation aggregation = newAggregation(
Aggregation.fields(""), //这一截是有问题的
lookup("wallpaper_get_success", "_id", "wallpaper_id", "success_id"),
match(Criteria.where("success_id").ne(new WallpaperGetSuccess[]{})),
sample(5)
);
原因:$addFields 在spring mongo中不支持
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
Aggregation myDocAggr = newAggregation(
match(Criteria.where("metaId.ref.uuid").is(someUUID)),
group("uuid").max("version").as("version"),
lookup("simple","execId.ref.uuid","uuid","simple"),
unwind("simple"),
new AggregationOperation(){
@Override
public Document toDocument(AggregationOperationContext aoc) {
return new Document("$addFields",new Document("metaId.ref.name","$simple.name"));
}
}
)
List mydocumentList=mongoTemplate.aggregate(myDocAggr,"myDocument",Document.class).getMappedResults();
2.解决方法
把addFields 改成 new Document
关键点: 引入的 Document 类是,而不是 spring-boot-data-mongo 中的,改为import org.bson.Document;
import org.bson.Document;//关键的引入
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.*;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
import org.springframework.data.mongodb.core.query.Collation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Component;
Aggregation aggregation = newAggregation(
aoc -> new Document("$addFields",new Document("_id",new Document("$toString","$_id"))),
lookup("wallpaper_get_success", "_id", "wallpaper_id", "success_id"),
match(Criteria.where("success_id").ne(new WallpaperGetSuccess[]{})),
sample(5)
);
不使用 lambda 表达式
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)