来自AI回答
在 Kotlin 中使用 MongoTemplate
(来自 Spring Data MongoDB)时,配置方式和 Java 是一致的,主要通过 MongoClientSettings
、MongoTemplate
Bean、以及 application.yml
配置完成。
✅ 一、MongoTemplate 的配置方式
你可以通过以下两种方式配置 MongoTemplate
:
✅ 方式 1:使用 @Configuration
+ Kotlin Bean 配置方式
kotlin
@Configuration
class MongoConfig {
@Value("\${spring.data.mongodb.uri}")
private lateinit var mongoUri: String
@Bean
fun mongoClient(): MongoClient {
return MongoClients.create(mongoUri)
}
@Bean
fun mongoTemplate(): MongoTemplate {
return MongoTemplate(mongoClient(), "your_database_name")
}
}
✅ 方式 2:完全使用 application.yml 配置 + 自动装配(推荐方式)
yaml
spring:
data:
mongodb:
uri: mongodb://username:password@host:port/database
Spring Boot 会自动配置 MongoClient
和 MongoTemplate
,你只需要在业务代码中 @Autowired
注入即可:
kotlin
@Autowired
lateinit var mongoTemplate: MongoTemplate
🌍 二、MongoTemplate 的时区处理
MongoDB 存储和读取时间默认使用 UTC 时区。
- MongoDB 本身不存储时区,只存储 ISODate 格式(UTC)。
MongoTemplate
默认也使用 UTC 时区进行读写(即Z
结尾的 ISO 8601 时间),除非你手动转换时间。
如果你在 Kotlin / Spring 中使用 java.util.Date
或 java.time
类型:
- 写入时
Date
或ZonedDateTime
会被转换为 UTC 格式。 - 读取时你拿到的时间仍是 UTC,需要你手动转换为本地时区。
✅ 示例:时间写入和读取转换(使用 Java 8 Time API)
kotlin
import java.time.ZonedDateTime
import java.time.ZoneId
import java.util.Date
val nowInAsia = ZonedDateTime.now(ZoneId.of("Asia/Taipei"))
val dateToSave = Date.from(nowInAsia.toInstant())
mongoTemplate.save(MyDocument(time = dateToSave))
读取后再转为本地时区:
kotlin
val document = mongoTemplate.findById(id, MyDocument::class.java)
val utcDate = document.time.toInstant()
val localTime = ZonedDateTime.ofInstant(utcDate, ZoneId.of("Asia/Taipei"))
✅ 三、补充建议
如果你频繁操作时间字段,建议:
- 后端存储全部用 UTC。
- 展示时统一转换为前端指定时区。
- 或者使用
@JsonFormat
统一序列化时区:
kotlin
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ssXXX", timezone = "Asia/Taipei")
val createdAt: Date? = null
是否需要我提供一个完整 Kotlin 示例,包括配置 + 写入 + 读取 + 时区转换逻辑?
作为pymongo 在进行聚类时可以这样做
MongoDB Aggregation 中 UTC 时间处理指南
方案:时区转换(精确)
python
# 转换为本地时区
count = collection.aggregate([
{
"$match": {"modelId": ObjectId("678502d829487203db")}
},
{
"$addFields": {
"localYear": {
"$year": {
"date": "$orderDate",
"timezone": "Asia/Shanghai"
}
},
"localMonth": {
"$month": {
"date": "$orderDate",
"timezone": "Asia/Shanghai"
}
}
}
},
{
"$group": {
"_id": {
"year": "$localYear",
"month": "$localMonth"
},
"totalQuantity": {"$sum": "$quantity"}
}
},
{
"$sort": {"_id.year": 1, "_id.month": 1}
}
])
注意事项
$year
和$month
的时区参数从 MongoDB 3.6+ 开始支持- 确保你的 PyMongo 版本 >= 3.6
- IANA 时区名称更可靠(如 "Asia/Shanghai")
- UTC 偏移量格式为 "+08:00" 或 "-05:00"
这些方法都能确保您的聚合查询正确处理 UTC 时间,并根据需要转换为本地时区进行统计。