在mongodb聚合中查找

在mongodb聚合中查找,第1张

在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);


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4959244.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-13
下一篇 2022-11-13

发表评论

登录后才能评论

评论列表(0条)

保存