栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在mongodb聚合中查找

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在mongodb聚合中查找

由于您具有嵌套数组,因此需要首先应用

$unwind

运算符,以便在使用
$lookup

管道之前对嵌入的文档进行反规范化(除非您已经在聚合操作中对其进行了展平):


db.personaddress.aggregate([    { "$unwind": "$address" },    { "$unwind": "$address.location" },    {        "$lookup": { "from": "places",  "localField": "address.location.place._id",  "foreignField": "_id",  "as": "address.location.place",         }    }])

然后可以实现为(未试用):

LookupOperation lookupOperation = LookupOperation.newLookup()    .from("places")    .localField("address.location.place._id")    .foreignField("_id")    .as("address.location.place");Aggregation agg = newAggregation(    unwind("address"),    unwind("address.location"),    lookupOperation  );AggregationResults<Outputdocument> aggResults = mongoTemplate.aggregate(    agg, PersonAddressdocument.class, Outputdocument.class);

如果您的Spring Data版本不支持此功能,则一种解决方法是实施
AggregationOperation
接口以接受

DBObject

public class CustomGroupOperation implements AggregationOperation {    private DBObject operation;    public CustomGroupOperation (DBObject operation) {        this.operation = operation;    }    @Override    public DBObject toDBObject(AggregationOperationContext context) {        return context.getMappedObject(operation);    }}

然后

$lookup

在聚合管道中将操作实现为DBObject:

DBObject lookupOperation = (DBObject)new BasicDBObject(    "$lookup", new BasicDBObject("from", "places")        .append("localField", "address.location.place._id")        .append("foreignField", "_id")        .append("as", "address.location.place")       );

然后可以将其用作:

Aggregation agg = newAggregation(    unwind("address"),    unwind("address.location"),    lookupOperation  );AggregationResults<Outputdocument> aggResults = mongoTemplate.aggregate(    agg, PersonAddressdocument.class, Outputdocument.class);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/387234.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号