1

以下BSON是personaddress集:查找MongoDB中聚集

{ 
     "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",  
        } 
       ] 
      } 
     ] 
    } 

我有一个又一个places集合:

{ 
    "_id":"VZG", 
    "name" : "vizag", 
    "district" : "Visakhaptanam, 
    "pincode" : "568923", 
} 

MongoDB中聚集使用查找,我要将places收集personaddress集合我试过使用

Aggregation aggregation = newAggregation(lookup("places", "address.location.place._id", "_id", "myplaces"), unwind("myplaces")); 

AggregationResults<OutputDocument> aggResults = mongoTemplate.aggregate(aggregation, PersonAddressDocument.class, OutputDocument.class); 

任何人都可以帮助我吗?

回答

1

既然你已经嵌套的数组,你需要首先应用$unwind运营商为了denormalise使用$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数据版本不支持这一点,解决方法是实施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 
); 
+1

非常感谢 – ShantiRadhkrishnan