以下bson是personaddress集合:{ id : 123456, name : foo, address : [{local : yes, location : [{place : {_id:VZG, }, place_lat : 18, place_lan : 83, },{place : {name : ...
以下bson是personaddress集合:
{
"id" : "123456",
"name" : "foo",
"address" : [
{
"local" : "yes",
"location" : [
{
"place" : {
"_id":"VZG",
},
"place_lat" : "18",
"place_lan" : "83",
},
{
"place" : {
"name" : "kerala",
"district" : "palakkad",
"pincode" : "5203689",
},
"place_lat" : "18",
"place_lan" : "83",
}
]
}
]
}
我有另一个地方集合:
{
"_id":"VZG",
"name" : "vizag",
"district" : "Visakhaptanam,
"pincode" : "568923",
}
在mongodb聚合中使用lookup,我想在personaddress集合中嵌入places集合
我试过用
Aggregation aggregation = newAggregation(lookup("places", "address.location.place._id", "_id", "myplaces"), unwind("myplaces"));
AggregationResults<OutputDocument> aggResults = mongoTemplate.aggregate(aggregation, PersonAddressDocument.class, OutputDocument.class);
谁能帮我?
解决方法:
由于您具有嵌套数组,因此在使用$lookup管道之前,需要首先应用$unwind运算符以使嵌入文档非规范化(除非您已在聚合操作中将它们展平):
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
);
编程基础网
本文标题为:java – 在mongodb聚合中查找
基础教程推荐
猜你喜欢
- Springboot下RedisTemplate的两种序列化方式实例详解 2023-05-24
- jsp实现局部刷新页面、异步加载页面的方法 2023-07-30
- Java全面细致讲解Wrapper的使用 2022-11-28
- javaweb实现投票系统 2023-05-18
- SpringCloud OpenFeign 服务调用传递 token的场景分析 2023-03-20
- JSP的response对象的实例详解 2023-07-31
- JSP 制作验证码的实例详解 2023-07-30
- Spring基于注解的缓存声明深入探究 2023-04-06
- Python实现短信循环压力测试教程 2023-10-08
- Java中比较Long类型是否相等 2023-10-08
