登录
首页 >  Golang >  Go问答

如何填充外部字段 ID 的 MongoDB 数组?

来源:stackoverflow

时间:2024-04-24 16:18:33 327浏览 收藏

学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《如何填充外部字段 ID 的 MongoDB 数组?》,以下内容主要包含等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!

问题内容

我的 mongodb 文档中有一个 objectid 数组,我想使用 go(特别是 mgo.v2)执行查询,用它们引用的文档中的数据填充它们。例如:

{
  _id: objectid("some_id"),
  events: [
    objectid("referenced_id_1"),
    objectid("referenced_id_2")
  ]
}

我希望查询返回以下格式的文档:

15536​​6893893

据我所知,我需要使用 $lookup 然后 $unwind,但似乎无法弄清楚。任何帮助将非常感激!谢谢:)


解决方案


我相信你想做这样的事情:

db.getCollection("some_collection").aggregate([
    { $match: { _id: ObjectId("some_id") } },

     // match events ids and then replace field "events" with the matching results
    { $lookup: {
            from: "referenced_collection",
            localField: "events",
            foreignField: "_id",
            as: "events"
    }}

    // there is no need for an $unwind step here since the expected output requires "events" to be an array
])

上面的查询使用了 $lookup 的简化版本,假设您不需要 pre-$project “事件”$lookup 结果,也不需要使用额外的匹配键。如果您确实需要这些东西,我建议您查看 mongodb 的文档以进行必要的改进。

以上就是《如何填充外部字段 ID 的 MongoDB 数组?》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>