Golang中MongoDB聚合查询无法获取Map字段问题求助
问题排查与修复
核心问题:投影阶段字段路径错误
你的聚合管道在$project阶段错误使用了$retconfig.value.policies作为字段路径,但通过$lookup关联返回的retconfig是完整的configuration文档对象,不存在value层级,直接访问$retconfig.policies即可获取目标字段。
修正后的聚合管道代码
lookupStage := bson.D{{"$lookup", bson.D{{"from", configcollection}, {"localField", "configId"}, {"foreignField", "_id"}, {"as", "retconfig"}}}} unwindStage := bson.D{{"$unwind", bson.D{{"path", "$retconfig"}, {"preserveNullAndEmptyArrays", false}}}} // 修正投影路径,移除多余的.value层级 project := bson.D{{"$project", bson.D{{"_id", 1}, {"retryPolicies", "$retconfig.policies"} }}} pipeline := mongo.Pipeline{lookupStage, unwindStage, project} r.store.Db.Collection("specialization").Aggregate(ctx, pipeline)
额外验证点
确认configuration集合中的文档确实包含policies字段,且specialization集合的configId与configuration的_id匹配无误,避免因数据不匹配导致关联后无有效数据返回。
内容的提问来源于stack exchange,提问作者EagerLearner
相关产品推荐
相关产品推荐

