如何在Spring Boot Reactive MongoDB中实现Mongo Shell的_id大于查询
_id: {$gt: ObjectId("...")} Query in Spring Boot Reactive MongoDB The problem with your current code is that you’re passing a raw string to the gt() method, but MongoDB’s _id field is of type ObjectId—not a string. This type mismatch means your query won’t match any documents, since it’s trying to compare an ObjectId value to a string.
Here’s the corrected implementation that properly mirrors your MongoDB Shell query:
Corrected Service Code
import org.bson.types.ObjectId; import org.springframework.data.mongodb.core.ReactiveMongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Service; import reactor.core.publisher.Flux; @Service public class MongoService { private final ReactiveMongoTemplate mongo; // Spring 4.3+ automatically injects constructor dependencies for final fields, no @Autowired needed public MongoService(ReactiveMongoTemplate mongo) { this.mongo = mongo; } public Flux<Device> getObjectsByTimestamp(String timestamp) { // Convert the string ObjectId to a proper ObjectId instance ObjectId targetObjectId = new ObjectId("5fd931e00000000000000000"); Query query = new Query(Criteria.where("_id").gt(targetObjectId)); return mongo.find(query, Device.class, "devices"); } }
Key Fixes Explained:
- Type Matching: We convert the hardcoded string
5fd931e00000000000000000into anObjectIdinstance. This matches the data type of your collection’s_idfield, so the greater-than comparison works exactly as it does in the MongoDB Shell. - Cleaner Dependency Injection: The
@Autowiredannotation is removed because Spring automatically handles constructor injection forfinalfields (Spring 4.3 and later). This is the recommended approach for dependency injection in Spring.
Bonus: Dynamic ObjectId from Timestamp
If your timestamp parameter is intended to generate the ObjectId (since MongoDB ObjectIds embed a Unix timestamp), you can create the ObjectId dynamically like this:
// Parse the input timestamp (assuming it's a Unix epoch in seconds) long epochSeconds = Long.parseLong(timestamp); ObjectId targetObjectId = new ObjectId(epochSeconds);
This will create an ObjectId where the timestamp portion matches your input, allowing you to query for documents created after that time.
内容的提问来源于stack exchange,提问作者RideSVEL

