灵活 Schema
用户行为数据结构多变(如点击、搜索、下单),MongoDB 的文档模型无需固定字段,适应快速迭代。
高吞吐写入
支持批量插入,适合高并发场景(如秒杀活动的用户操作记录)。
复杂查询优化
支持聚合管道、地理空间查询、全文索引,便于多维分析。
水平扩展
通过分片(Sharding)应对海量数据存储。
user_actions
){
"userId": "6582a1d4f12e6c5a9f4b3c7d",
"sessionId": "sess_abc123",
"actionType": "PRODUCT_VIEW", // 枚举:VIEW、CLICK、ADD_TO_CART、PURCHASE
"targetId": "prod_12345", // 商品/页面ID
"timestamp": ISODate("2023-12-20T08:30:00Z"),
"metadata": { // 动态扩展字段
"searchKeyword": "智能手机",
"pageFrom": "/home",
"deviceType": "MOBILE"
}
}
user_profiles
){
"userId": "6582a1d4f12e6c5a9f4b3c7d",
"lastLogin": ISODate("2023-12-20T08:30:00Z"),
"favoriteCategories": ["电子产品", "家居"],
"behaviorStats": {
"totalPurchases": 15,
"avgCartValue": 299.99
}
}
org.springframework.boot
spring-boot-starter-data-mongodb
# application.yml
spring:
data:
mongodb:
uri: mongodb://admin:password@localhost:27017/ecommerce
@Document(collection = "user_actions")
public class UserAction {
@Id
private String id;
private String userId;
private String actionType;
private String targetId;
private Date timestamp;
private Map metadata;
// Getters & Setters
}
// 自定义查询
public interface UserActionRepository extends MongoRepository {
List findByUserIdAndActionType(String userId, String actionType);
}
// 复杂操作使用 MongoTemplate
@Autowired
private MongoTemplate mongoTemplate;
public void logAction(UserAction action) {
mongoTemplate.insert(action);
}
// 统计用户最近30天的加购次数
Aggregation agg = Aggregation.newAggregation(
Aggregation.match(Criteria.where("userId").is(userId)
.and("actionType").is("ADD_TO_CART")
.and("timestamp").gte(LocalDateTime.now().minusDays(30))),
Aggregation.group().count().as("totalAddToCart")
);
AggregationResults
// 聚合查询销量Top10商品
Aggregation agg = Aggregation.newAggregation(
Aggregation.match(Criteria.where("actionType").is("PURCHASE")),
Aggregation.group("targetId").count().as("totalSales"),
Aggregation.sort(Sort.Direction.DESC, "totalSales"),
Aggregation.limit(10)
);
利用 $graphLookup
分析用户行为序列:
Aggregation agg = Aggregation.newAggregation(
Aggregation.match(Criteria.where("userId").is(userId)),
Aggregation.sort(Sort.Direction.ASC, "timestamp"),
Aggregation.graphLookup("user_actions")
.startWith("$targetId")
.connectFrom("targetId")
.connectTo("previousTargetId")
.maxDepth(5)
.as("navigationPath")
);
索引策略
// 为高频查询字段创建组合索引
mongoTemplate.indexOps("user_actions").ensureIndex(
new Index().on("userId", Sort.Direction.ASC)
.on("timestamp", Sort.Direction.DESC)
);
TTL 自动过期
自动删除30天前的日志:
@Document(collection = "user_actions")
public class UserAction {
@Indexed(expireAfterSeconds = 2592000) // 30天
private Date timestamp;
}
分片策略
按 userId
哈希分片,分散写入压力。
通过 MongoDB Atlas Charts 直接生成用户行为仪表盘。
集成 Spring Boot 与 Elasticsearch + Kibana 进行高级分析。
隐私合规:记录行为时需脱敏处理(如加密 userId
)。
异步写入:高并发时通过 Kafka 缓冲数据,批量写入 MongoDB。
存储成本:归档旧数据至冷存储(如 S3)。
通过 MongoDB 的灵活存储和 Spring Data 的高效集成,可构建强大的用户行为分析系统,直接驱动精准营销和用户体验优化。