Random documents from MongoDB using spring-data

后端 未结 2 824
萌比男神i
萌比男神i 2021-01-13 13:18

I\'m able to do it by using this mongodb native query:

db.books.aggregate(
   [ { $sample: { size: 15 } } ]
)

But how to do it in spr

2条回答
  •  天命终不由人
    2021-01-13 13:34

    Blakes Seven answered it correctly, however, I want to offer a nicer implementation of AggregationOperation, which follows standard Spring implementation

    import com.mongodb.BasicDBObject;
    import com.mongodb.DBObject;
    import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
    import org.springframework.data.mongodb.core.aggregation.AggregationOperationContext;
    import org.springframework.data.mongodb.core.query.Criteria;
    import org.springframework.util.Assert;
    
    public class SampleOperation implements AggregationOperation  {
    
        private int size;
    
        public SampleOperation(int size) {
            Assert.isTrue(size > 0, " Size must be positive!");
            this.size = size;
        }
    
        public AggregationOperation setSize(int size) {
            Assert.isTrue(size > 0, " Size must be positive!");
            this.size = size;
            return this;
        }
    
        @Override
        public DBObject toDBObject(AggregationOperationContext context) {
            return new BasicDBObject("$sample", context.getMappedObject(Criteria.where("size").is(size).getCriteriaObject()));
        }
    
    }
    

    After that, you can create SampleOperation object with constructor, or later change the size of it by setSize() method, and apply it to aggregate() function as normal.

    Update: In SpringBoot 2.0.0+ and Spring Framework 5.0: Spring Mongo drop DBObject and replace by org.bson.Document therefore the last past should be updated as:

        @Override
    public Document toDocument(AggregationOperationContext aggregationOperationContext) {
        return new Document("$sample", aggregationOperationContext.getMappedObject(Criteria.where("size").is(size).getCriteriaObject()));
    

    }

    And remove the @Override toDBObject

提交回复
热议问题