论坛的首页会列出很多主题,每个主题的 浏览量和回复数的统计是一个难题。 如果 挨个去调用函数获取,效率太低。 访问量也大。
所以需要用一天 数据库指令解决
下面是用AI 打磨很好几个小时,可以工作的结果:
let test = [ { "$match": { "tags": { "$elemMatch": { "0": "t", "1": "create_post" } } } }, { "$match": { "tags": { "$elemMatch": { "0": "topicid", "1": { "$in": [ "153489740703bf2301bedd92045856f85e1e5f5bd166d0d4a780e1d5411d1452", "3f32c818569a58352235ec13d9bf66e827545eaf23607d04c3181b91f974cbd0" ] } } } } }, { "$addFields": { "topicId": { "$reduce": { "input": "$tags", "initialValue": null, "in": { "$cond": [ { "$and": [ { "$eq": [{ "$arrayElemAt": ["$$this", 0] }, "topicid"] } ] }, { "$arrayElemAt": ["$$this", 1] }, // 返回数组的第二个元素 "$$value" ] } } } } }, { "$group": { "_id": "$topicId", "count": { "$sum": 1 } } }, { "$project": { "_id": 0, "topicId": "$_id", "count": 1 } } ];有了这个例子, 我们再用js程序 翻译
const pipeline = []; let filter = countEvent.filter let statTagKey = filter[0] let statTagValues = filter[1] // 1️ 固定条件(如 t=create_post) // 1️ 固定条件(如 t=create_post) if (countEvent.tags) { let tags = countEvent.tags; tags.map(tag => { pipeline.push({ $match: { tags: { $elemMatch: { 0: tag[0], 1: tag[1] } } } }); }); } // 2️ 必须包含统计维度 key(topicid / pid) pipeline.push({ $match: { tags: { $elemMatch: { 0: statTagKey , "1": {"$in": statTagValues} } } } }); // 3️ 提取统计值(修复 $isArray 使用) pipeline.push({ "$addFields": { "targetid": { "$reduce": { "input": "$tags", "initialValue": null, "in": { "$cond": [ { "$and": [ { "$eq": [{ "$arrayElemAt": ["$$this", 0] }, statTagKey] } ] }, { "$arrayElemAt": ["$$this", 1] }, // 返回数组的第二个元素 "$$value" ] } } } } }); // 5️ 分组统计 pipeline.push({ $group: { _id: '$targetid', count: { $sum: 1 } } }); // 6️ 输出格式 pipeline.push({ $project: { _id: 0, targetid: '$_id', count: 1 } }); console.log(console.log(JSON.stringify(pipeline, (key, value) => { // 处理特殊值 return value; }, 2))); const result = await eventsCollection.aggregate(pipeline).toArray(); return { code: 200, message: '统计成功', counts: result };最后就可以得到每个id 多少条 回复了。
