在使用 MongoDB 和 Golang 进行查找的引用中获取值

Elw*_*wyn 4 go mongodb mgo

我有下面的结构。我使用Golang 1.9.2

// EventBoost describes the model of a EventBoost
type EventBoost struct {
  ID          string    `bson:"_id" json:"_id" valid:"alphanum,printableascii"`
  CampaignID  string    `bson:"_campaign_id" json:"_campaign_id" valid:"alphanum,printableascii"`
  Name        string    `bson:"name" json:"name"`
  Description string    `bson:"description" json:"description"`
  Level       string    `bson:"level" json:"level"`
  EventID     string    `bson:"_event_id" json:"_event_id" valid:"alphanum,printableascii"`
  StartDate   time.Time `bson:"start_date" json:"start_date"`
  EndDate     time.Time `bson:"end_date" json:"end_date"`
  IsPublished bool      `bson:"is_published" json:"is_published"`
  CreatedBy   string    `bson:"created_by" json:"created_by"`
  CreatedAt   time.Time `bson:"created_at" json:"created_at"`
  ModifiedAt  time.Time `bson:"modified_at" json:"modified_at"`
}

// LocationBoost describes the model of a LocationBoost
type LocationBoost struct {
  ID          string    `bson:"_id" json:"_id" valid:"alphanum,printableascii"`
  CampaignID  string    `bson:"_campaign_id" json:"_campaign_id" valid:"alphanum,printableascii"`
  Name        string    `bson:"name" json:"name"`
  Description string    `bson:"description" json:"description"`
  Level       string    `bson:"level" json:"level"`
  LocationID  string    `bson:"_location_id" json:"_location_id" valid:"alphanum,printableascii"`
  StartDate   time.Time `bson:"start_date" json:"start_date"`
  EndDate     time.Time `bson:"end_date" json:"end_date"`
  IsPublished bool      `bson:"is_published" json:"is_published"`
  CreatedBy   string    `bson:"created_by" json:"created_by"`
  CreatedAt   time.Time `bson:"created_at" json:"created_at"`
  ModifiedAt  time.Time `bson:"modified_at" json:"modified_at"`
}

// Campaign describes the model of a Campaign
type Campaign struct {
    ID               string           `bson:"_id" json:"_id" valid:"alphanum,printableascii"`
    Name             string           `bson:"name" json:"name"`
    Description      string           `bson:"description" json:"description"`
    EventBoostIDs    []string         `bson:"event_boost_ids" json:"event_boost_ids"`
    LocationBoostIDs []string         `bson:"location_boost_ids" json:"location_boost_ids"`
    StartDate        time.Time        `bson:"start_date" json:"start_date"`
    EndDate          time.Time        `bson:"end_date" json:"end_date"`
    IsPublished      bool             `bson:"is_published" json:"is_published"`
    CreatedBy        string           `bson:"created_by" json:"created_by"`
    CreatedAt        time.Time        `bson:"created_at" json:"created_at"`
    ModifiedAt       time.Time        `bson:"modified_at" json:"modified_at"`
}
Run Code Online (Sandbox Code Playgroud)

一个活动(了解营销活动)是由事件地点可以与(基本或溢价)的水平而提高。广告系列有开始和结束日期,因此也有提升。

该函数GetEventLevel必须返回给定事件的级别。

// GetEventLevel of an event
func (dao *campaignDAO) GetEventLevel(eventID string) (string, error) {
}
Run Code Online (Sandbox Code Playgroud)

如果事件在推动积极运动isPublishedtrue),而升压活跃isPublishedtrue)和现在的日期是升压的开始和结束日期之间,那么我的事件推动,因此该函数返回的水平(基本或溢价)。否则,它返回"standard"

我的问题是:我可以用 Mongo 完全做到这一点吗?或者我是否需要使用 Golang 在 DAO 中执行一些逻辑?

如果我可以用 Mongo 做到这一点,我所希望的是,我不知道该怎么做。据我所知,我首先需要查找活动的事件和位置,然后使用日期在其中进行搜索,但是..

icz*_*cza 5

这样做(和最困难的部分),你想要可以很容易地在MongoDB中做什么。最有可能返回“基本”、“高级”或“标准”的最后一步也可以完成,但我认为这不值得麻烦,因为这在 Go 中是微不足道的。

在 MongoDB 中,为此使用聚合框架。这可以mgo通过Collection.Pipe()方法在包中获得。您必须将切片传递给它,每个元素对应一个聚合阶段。阅读此答案以获取更多详细信息:如何从 MongoDB 集合中获取聚合

回到你的例子。你的GetEventLevel()方法可以这样实现:

func (dao *campaignDAO) GetEventLevel(eventID string) (string, error) {
    c := sess.DB("").C("eventboosts") // sess represents a MongoDB Session
    now := time.Now()
    pipe := c.Pipe([]bson.M{
        {
            "$match": bson.M{
                "_event_id":    eventID,            // Boost for the specific event
                "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":         "campaigns",
                "localField":   "_campaign_id",
                "foreignField": "_id",
                "as":           "campaign",
            },
        },
        {"$unwind": "$campaign"},
        {
            "$match": bson.M{
                "campaign.is_published": true,      // Attached campaign is active
            },
        },
    })

    var result []*EventBoost
    if err := pipe.All(&result); err != nil {
        return "", err
    }
    if len(result) == 0 {
        return "standard", nil
    }
    return result[0].Level, nil
}
Run Code Online (Sandbox Code Playgroud)

如果您最多只需要一个EventBoost(或者可能不会同时有多个),请使用$limitstage 将结果限制为一个,并且使用$project仅获取该level字段,仅此而已。

使用此管道进行上述简化/优化:

pipe := c.Pipe([]bson.M{
    {
        "$match": bson.M{
            "_event_id":    eventID,            // Boost for the specific event
            "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":         "campaigns",
            "localField":   "_campaign_id",
            "foreignField": "_id",
            "as":           "campaign",
        },
    },
    {"$unwind": "$campaign"},
    {
        "$match": bson.M{
            "campaign.is_published": true,      // Attached campaign is active
        },
    },
    {"$limit": 1},             // Fetch at most 1 result
    {
        "$project": bson.M{
            "_id":   0,        // We don't even need the EventBoost's ID
            "level": "$level", // We do need the level and nothing more
        },
    },
})
Run Code Online (Sandbox Code Playgroud)