MongoDB
 sql >> Baza danych >  >> NoSQL >> MongoDB

wyszukiwanie w agregacji mongodb

Ponieważ masz zagnieżdżone tablice, musisz zastosować $unwind najpierw operator w celu denormalizacji osadzonych dokumentów przed użyciem $lookup potok (chyba że spłaszczyłeś je już w swojej operacji agregacji):

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

które można następnie zaimplementować jako (nietestowane):

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

Jeśli Twoja wersja Spring Data tego nie obsługuje, obejściem jest wdrożenie AggregationOperation interfejs do przyjęcia 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);
    }
}

Następnie zaimplementuj $lookup działanie jako DBObject w potoku agregacji:

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

którego możesz następnie użyć jako:

Aggregation agg = newAggregation(
    unwind("address"),
    unwind("address.location"),
    lookupOperation  
);

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


  1. Redis
  2.   
  3. MongoDB
  4.   
  5. Memcached
  6.   
  7. HBase
  8.   
  9. CouchDB
  1. Długość wartości pola tekstowego w mongoDB

  2. 6 sposobów na uzyskanie roku z daty w MongoDB

  3. (MongoDB Java) $wciśnij do tablicy

  4. Automatyzacja i zarządzanie MongoDB w chmurze

  5. MongoDB $pomnóż