基於 MongoTemplate 的兩種核心查詢場景代碼片段。
public Price queryPriceById(String id) throws Exception {
return mongoTemplate.findById(new ObjectId(id), Price.class, PRICE_COLLECTION);
}
ObjectId 需導入 org.bson.types.ObjectId,PRICE_COLLECTION 為集合名常量。
public Price queryPriceByName(String name) throws Exception {
Query query = new Query(Criteria.where("name").is(name));
return mongoTemplate.findOne(query, Price.class, PRICE_COLLECTION);
}
Criteria.where("field").is(value) 構建等值條件,支持鏈式調用組合多條件(.and("age").gt(18))。
find(query, clazz, collection):返回列表findAndModify(query, update, clazz, collection):原子更新並返回舊/新文檔upsert(query, update, clazz, collection):不存在則插入remove(query, clazz, collection):刪除匹配文檔建議封裝通用 Repository 基類,減少樣板代碼。