Only return the looked up document with Mongo and Golang

旧巷老猫 提交于 2019-12-08 03:18:26

You may use $unwind to "transform" the event array field to a single embedded document, then $replaceRoot to "promote" this event field to be the new "root":

pipe := session.DB(shared.DatabaseNamespace).C(dao.collection).Pipe([]bson.M{
    {
        "$match": bson.M{
            "is_published": true,               // Boost is active
            "start_date":   bson.M{"$lt": now}, // now is between start and end
            "end_date":     bson.M{"$gt": now}, // now is between start and end
        },
    },
    {
        "$lookup": bson.M{
            "from":         "events",
            "localField":   "_event_id",
            "foreignField": "_id",
            "as":           "event",
        },
    },
    {"$unwind": "$event"},
    {"$replaceRoot": bson.M{ "newRoot": "$event" }},
})

This solution handles properly if there are multiple events for a given EventBoost.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!