Find all embedded documents from manual reference in MongoDB

前端 未结 1 569
伪装坚强ぢ
伪装坚强ぢ 2021-01-25 02:33

I use MongoDB and Spring Boot in a project. I used manual reference to point out a collection, My structure is as follows:

Reel collection



        
相关标签:
1条回答
  • 2021-01-25 03:22

    Your JSON stored in database has wrong structure. Your Reel class expects list of Category, but in database you have stored as nested object.

    You need to add this stage just after $lookup

    {
      "$addFields": {
        "category": {
          "$map": {
            "input": "$category.videos",
            "in": {
              "videos": "$$this"
            }
          }
        }
      }
    }
    

    Java code

    public List<Reel> findById(String _id) {
    
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("_id").is(_id)),
                Aggregation.lookup(mongoTemplate.getCollectionName(Video.class), "category.videos", "_id", "category.videos"),
                new AggregationOperation() {
    
                    @Override
                    public Document toDocument(AggregationOperationContext context) {
                        return new Document("$addFields",
                                new Document("category", new Document("$map", new Document("input", "$category.videos")
                                        .append("in", new Document("videos", "$$this")))));
                    }
                })
            .withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());
    
        LOG.debug(
                aggregation.toString().replaceAll("__collection__", mongoTemplate.getCollectionName(Reel.class)));
    
        return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(Reel.class), Reel.class)
                .getMappedResults();
    
    }
    

    Recomendations

    1. Do not hard-code collection name, use better mongoTemplate.getCollectionName method
    2. Always log aggregation pipeline before performing, it helps debugging.
    3. If your collection will grow in the future, use {allowDiskUse: true} MongoDb aggregation option.
    0 讨论(0)
提交回复
热议问题