You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring Boot Reactive MongoDB中实现Mongo Shell的_id大于查询

How to Replicate MongoDB Shell's _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 5fd931e00000000000000000 into an ObjectId instance. This matches the data type of your collection’s _id field, so the greater-than comparison works exactly as it does in the MongoDB Shell.
  • Cleaner Dependency Injection: The @Autowired annotation is removed because Spring automatically handles constructor injection for final fields (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:54:54