dongshengli6384 2018-01-09 08:06
浏览 104
已采纳

在MongoDB和Golang的查询参考中获取值

I have the structures below. I use 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"`
}

A Campaign (understand a marketing campaign) is made of Events or Locations that can be boosted with a level (basic or premium). A campaign has a start and a end date, so do have the boosts.

The function GetEventLevel has to return me the level of a given event.

// GetEventLevel of an event
func (dao *campaignDAO) GetEventLevel(eventID string) (string, error) {
}

If the event is boosted in an active campaign (isPublished is true), and the boost is active (isPublished is true) and the now date is between the start and end date of the boost, then my Event is boosted, so the function returns the level (basic or premium). Else, it returns "standard".

My question is : can I do this fully with Mongo ? Or do I need to perform some logic in the DAO with Golang ?

If I can do this with Mongo, what I hope, I have no idea how to do this. From what I understand, I would first need to lookup the events and the locations of the campaign, and then search in it with dates, but..

  • 写回答

2条回答 默认 最新

  • dsqtl335227 2018-01-09 18:04
    关注

    Doing most (and the hardest part) of what you want can easily be done in MongoDB. The final step when returning "basic", "premium" or "standard" most likely can also be done, but I think it's not worth the hassle as that is trivial in Go.

    In MongoDB use the Aggregation framework for this. This is available in the mgo package via the Collection.Pipe() method. You have to pass a slice to it, each element corresponds to an aggregation stage. Read this answer for more details: How to Get an Aggregate from a MongoDB Collection

    Back to your example. Your GetEventLevel() method could be implemented like this:

    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
    }
    

    If you only need at most one EventBoost (or there may not be more at the same time), use $limit stage to limit results to a single one, and use $project to only fetch the level field and nothing more.

    Use this pipeline for the above mentioned simplification / optimization:

    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
            },
        },
    })
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况