sql >> Database teknologi >  >> NoSQL >> MongoDB

opslag i mongodb aggregering

Da du har indlejrede arrays, skal du anvende $unwind operatør først for at denormalisere de indlejrede dokumenter, før du bruger $lookup pipeline (medmindre du allerede har udjævnet dem i din aggregeringsoperation):

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

som derefter kan implementeres som (utestet):

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

Hvis din Spring Data-version ikke understøtter dette, er en løsning at implementere AggregationOperation grænseflade til at tage et DBObject ind :

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

Implementer derefter $lookup drift som et DBO-objekt i aggregeringspipelinen:

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

som du derefter kan bruge som:

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

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


  1. Lagring af nøgler med præfiks, der udløber i redis

  2. ServiceStack:Genindsæt pipeline, når du kalder en tjeneste manuelt?

  3. Forstå MongoDB Backup Options

  4. elasticsearch v.s. MongoDB til filtreringsapplikation