当前位置: 首页>>代码示例>>Golang>>正文


Golang mgo.Database类代码示例

本文整理汇总了Golang中labix/org/v2/mgo.Database的典型用法代码示例。如果您正苦于以下问题:Golang Database类的具体用法?Golang Database怎么用?Golang Database使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Database类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: ForkPrivate

// Fork current private template into an other private one.
// Copies the whole directory from /templates/private/{host}/{current_template} to /templates/private/{host}/{inp:new_private_name}
func ForkPrivate(db *mgo.Database, opt map[string]interface{}, inp map[string][]string, root, host string) error {
	if scut.TemplateType(opt) != "private" {
		return fmt.Errorf("Your current template is not a private one.") // Kinda unsensical error message but ok...
	}
	rule := map[string]interface{}{
		"new_template_name": "must",
	}
	dat, e_err := extract.New(rule).Extract(inp)
	if e_err != nil {
		return e_err
	}
	new_template_name := dat["new_template_name"].(string)
	to := filepath.Join(root, "templates", "private", host, new_template_name)
	e, e_err := Exists(to)
	if e_err != nil {
		return fmt.Errorf("Can't determine if private template exists.")
	}
	if e {
		return fmt.Errorf("Private template named %v already exists.", new_template_name)
	}
	from := filepath.Join(root, "templates", "private", host, scut.TemplateName(opt))
	copy_err := copyrecur.CopyDir(from, to)
	if copy_err != nil {
		return fmt.Errorf("There was an error while copying.")
	}
	id := basic.CreateOptCopy(db)
	q := m{"_id": id}
	upd := m{
		"$set": m{
			"Template": new_template_name,
		},
	}
	return db.C("options").Update(q, upd)
}
开发者ID:Laller,项目名称:hypecms,代码行数:36,代码来源:template_editor.go

示例2: GetPeerOutCallsAndDurationForDay

func GetPeerOutCallsAndDurationForDay(day string, peer string, mongoDb *mgo.Database) bson.M {
	collection := mongoDb.C("dailypeer_outgoing")
	results := bson.M{}
	startDate, err := time.Parse(time.RFC3339, day)
	if err != nil {
		panic(err)
	}
	startDayDate := time.Date(startDate.Year(), startDate.Month(), startDate.Day(), 0, 0, 0, 0, time.UTC)
	endDayDate := time.Date(startDate.Year(), startDate.Month(), startDate.Day(), 23, 59, 59, 0, time.UTC)

	var myMatch bson.M

	if len(peer) > 0 {
		myMatch = bson.M{
			"$match": bson.M{
				"metadata.dt":          bson.M{"$gte": startDayDate, "$lte": endDayDate},
				"metadata.dst":         bson.RegEx{peer, "i"},
				"metadata.disposition": 16,
			},
		}
	} else {
		myMatch = bson.M{
			"$match": bson.M{
				"metadata.dt":          bson.M{"$gte": startDayDate, "$lte": endDayDate},
				"metadata.disposition": 16,
			},
		}
	}

	//
	myProject := bson.M{
		"$project": bson.M{
			"_id":      0,
			"calls":    "$calls",
			"duration": "$duration",
		},
	}

	myGroup := bson.M{
		"$group": bson.M{
			"_id":                 0,
			"outCallsNumber":      bson.M{"$sum": "$calls"},
			"outCallsDuration":    bson.M{"$sum": "$duration"},
			"outCallsAvgDuration": bson.M{"$avg": "$duration"},
		},
	}

	//
	operations := []bson.M{myMatch, myProject, myGroup}
	pipe := collection.Pipe(operations)
	err = pipe.One(&results)
	if err != nil {
		results["outCallsNumber"] = 0
		results["outCallsDuration"] = 0
		results["outCallsAvgDuration"] = 0
		return results
	}

	return results
}
开发者ID:vassilux,项目名称:revor,代码行数:60,代码来源:peer.go

示例3: GetBattleAnswerRecs

func GetBattleAnswerRecs(db *mgo.Database, query interface{}) []BattleAnswerRec {
	var recs []BattleAnswerRec

	db.C("battle_answers").Find(query).All(&recs)

	return recs
}
开发者ID:jameycribbs,项目名称:battle_answers_go,代码行数:7,代码来源:battle_answer.go

示例4: updateMachine

// this method responds to client updates
// the json data is part of the post request body, we parse
//   it and...
//   1. set the id to the serial
//   2. convert the softwareoutput to html using template.html
//   3. upsert the data into the database
func updateMachine(w http.ResponseWriter, r *http.Request, db *mgo.Database, argPos int) {
	if r.Method != "POST" {
		http.Error(w, "only accepts POST requests", 405)
	}

	body, err := ioutil.ReadAll(r.Body)
	defer r.Body.Close()
	var m machine
	err = json.Unmarshal(body, &m)
	if err != nil {
		fmt.Println(err)
		return
	}

	m.Now = time.Now()
	m.Softwareoutput = template.HTML(strings.Replace(string(m.Softwareoutput), "\n", "<br>", -1))

	fmt.Printf("%v: Connection from %v - ip: %v\n", m.Now, m.Hostname, m.Ip)

	_, err = db.C("machines").UpsertId(m.Id, m)
	if err != nil {
		fmt.Println(err)
	}

	return
}
开发者ID:paddie,项目名称:SOxServer,代码行数:32,代码来源:machine.go

示例5: GetGameRecs

func GetGameRecs(db *mgo.Database, query interface{}) []GameRec {
	var recs []GameRec

	db.C("games").Find(query).All(&recs)

	return recs
}
开发者ID:jameycribbs,项目名称:battle_answers_go,代码行数:7,代码来源:game.go

示例6: DoPaging

// png = path and query
// In the CMS you can access it from uni.P + "?" + uni.Req.URL.RawQuery.
func DoPaging(db *mgo.Database, collection string, query map[string]interface{}, page_num_key string, get map[string][]string, pnq string, limit int) PagingInfo {
	var current_page int
	num_str, has := get[page_num_key]
	if !has {
		current_page = 1
	} else {
		val, err := strconv.ParseInt(num_str[0], 10, 32)
		if err == nil {
			current_page = int(val)
		} else {
			current_page = 1
		}
	}
	all_results, _ := db.C(collection).Find(query).Count() // TODO: think about the error here.
	nav, _ := paging.P(current_page, all_results/limit+1, 3, pnq)
	skip := (current_page - 1) * limit
	return PagingInfo{
		Result:       nav,
		Skip:         skip,
		Current_page: current_page,
		Limit:        limit,
		All_results:  all_results,
		Paramkey:     page_num_key,
		Url:          pnq,
	}
}
开发者ID:Laller,项目名称:hypecms,代码行数:28,代码来源:display_model.go

示例7: deleteMachine

/***********************************
delete a machine given machine_id
************************************/
func deleteMachine(w http.ResponseWriter, r *http.Request, db *mgo.Database, argPos int) {
	machine_id := r.URL.Path[argPos:]
	if len(machine_id) == 0 {
		http.Redirect(w, r, "/", 302)
	}
	fmt.Println("Deleting machine: ", machine_id)
	col_m := db.C("machines")

	var m *machine
	err := col_m.Find(bson.M{"_id": machine_id}).One(&m)

	if err != nil {
		fmt.Print(err)
		return
	}

	_, err = db.C("old_machines").Upsert(bson.M{"hostname": m.Hostname}, m)

	if err != nil {
		fmt.Print(err)
	}

	err = col_m.Remove(bson.M{"_id": machine_id})

	if err != nil {
		fmt.Print(err)
	}

	http.Redirect(w, r, "/", 302)
	return
}
开发者ID:paddie,项目名称:SOxServer,代码行数:34,代码来源:machine.go

示例8: Node

// 主题所属节点
func (t *Topic) Node(db *mgo.Database) *Node {
	c := db.C("nodes")
	node := Node{}
	c.Find(bson.M{"_id": t.NodeId}).One(&node)

	return &node
}
开发者ID:hello-kukoo,项目名称:gopher,代码行数:8,代码来源:models.go

示例9: Sites

// 分类下的所有站点
func (sc *SiteCategory) Sites(db *mgo.Database) *[]Site {
	var sites []Site
	c := db.C("contents")
	c.Find(bson.M{"categoryid": sc.Id_, "content.type": TypeSite}).All(&sites)

	return &sites
}
开发者ID:hello-kukoo,项目名称:gopher,代码行数:8,代码来源:models.go

示例10: FindContent

// Called from Front hook.
// Find slug value by given key.
func FindContent(db *mgo.Database, keys []string, val string) (map[string]interface{}, bool) {
	query := bson.M{}
	if len(keys) == 0 {
		return nil, false
	} else if len(keys) == 1 {
		if keys[0] == "_id" && len(val) == 24 { // TODO: check for validity of id.
			query[keys[0]] = bson.ObjectIdHex(val)
		} else {
			query[keys[0]] = val
		}
	} else {
		or := []map[string]interface{}{}
		for _, v := range keys {
			if v == "_id" && len(v) == 24 { // TODO: check fir validity of id.
				or = append(or, map[string]interface{}{v: bson.ObjectIdHex(val)})
			} else {
				or = append(or, map[string]interface{}{v: val})
			}
		}
		query["$or"] = or
	}
	var v interface{}
	db.C(Cname).Find(query).One(&v)
	if v == nil {
		return nil, false
	}
	return basic.Convert(v).(map[string]interface{}), true
}
开发者ID:Laller,项目名称:hypecms,代码行数:30,代码来源:content_model.go

示例11: Unvote

// Checks if unvotes are approved at all. Returns error if not.
// Checks if vote option is legal.
// Checks if user indeed voted to that option. Return error if not.
// Decreases the counter field of the given vote option, and pulls the user_id from the field of the given vote option.
func Unvote(db *mgo.Database, user, action map[string]interface{}, inp map[string][]string) error {
	can_unvote, has_cu := action["can_unvote"]
	if !has_cu || can_unvote.(bool) == false {
		return fmt.Errorf("Can't unvote.")
	}
	dat, collection, _, input_vote, err := sharedProc(action, inp)
	if err != nil {
		return err
	}
	doc_id := patterns.ToIdWithCare(dat["document_id"].(string))
	user_id := user["_id"].(bson.ObjectId)
	q := m{"_id": doc_id, input_vote: user_id}
	count, err := db.C(collection).Find(q).Count()
	if err != nil {
		return err
	}
	if count != 1 {
		return fmt.Errorf("Can't unvote a doc which you haven't vote on yet.")
	}
	q = m{"_id": doc_id}
	upd := m{
		"$inc": m{
			input_vote + "_count": -1,
		},
		"$pull": m{
			input_vote: user_id,
		},
	}
	return db.C(collection).Update(q, upd)
}
开发者ID:Laller,项目名称:hypecms,代码行数:34,代码来源:vote.go

示例12: AdCode

func (u *Utils) AdCode(position string, db *mgo.Database) template.HTML {
	c := db.C(ADS)
	var ad AD
	c.Find(bson.M{"position": position}).Limit(1).One(&ad)

	return template.HTML(ad.Code)
}
开发者ID:hello-kukoo,项目名称:gopher,代码行数:7,代码来源:views.go

示例13: Init

func (ms *MongodbService) Init(session *mgo.Session, db *mgo.Database, coll string) {
	ms.session = session
	ms.db = db
	ms.c = db.C(coll)
	ms.coll = coll
	ms.mutex = new(sync.Mutex)
}
开发者ID:kicool,项目名称:CrazyTestor,代码行数:7,代码来源:mongodb.go

示例14: GetBeReferenceLi

//reference:[[dataSource, dataSet, fieldName, id], [dataSource, dataSet, fieldName, id]]
//beReference:[[dataSource, dataSet, fieldName, id], [dataSource, dataSet, fieldName, id]]
func (o UsedCheck) GetBeReferenceLi(db *mgo.Database, fieldGroup FieldGroup, relationItem RelationItem, data *map[string]interface{}) []interface{} {
	sourceLi := []interface{}{}
	relationId, err := strconv.Atoi(fmt.Sprint((*data)[fieldGroup.Id]))
	if err != nil {
		panic(err)
	}
	if relationItem.RelationDataSetId == "A" {
		sourceLi = append(sourceLi, []interface{}{relationItem.RelationModelId, "A", "id", relationId})
		return sourceLi
	}

	refData := map[string]interface{}{}
	query := map[string]interface{}{
		relationItem.RelationDataSetId + ".id": relationId,
	}
	//{"B.id": 2}
	err = db.C(relationItem.RelationModelId).Find(query).One(&refData)
	if err != nil {
		panic(err)
	}
	masterData := refData["A"].(map[string]interface{})
	masterDataId, err := strconv.Atoi(fmt.Sprint(masterData["id"]))
	if err != nil {
		panic(err)
	}
	sourceLi = append(sourceLi, []interface{}{relationItem.RelationModelId, "A", "id", masterDataId})

	sourceLi = append(sourceLi, []interface{}{relationItem.RelationModelId, relationItem.RelationDataSetId, "id", relationId})
	return sourceLi
}
开发者ID:hongjinqiu,项目名称:finance,代码行数:32,代码来源:UsedCheck.go

示例15: GetResource

// Retrieve an instance of the resource given the id. Assumes the resource name matches the collection name
func GetResource(p martini.Params, r render.Render, db *mgo.Database) {
	resource := p["resource"]
	id := p["id"]

	// TODO use reflection
	var result *interface{}
	if !bson.IsObjectIdHex(id) {
		r.JSON(400, map[string]string{"error": "Invalid id"})
		return
	}

	err := db.C(resource).Find(bson.M{"_id": bson.ObjectIdHex(id)}).One(&result)
	if err != nil {
		var status int
		if err == mgo.ErrNotFound {
			status = 404
		} else {
			status = 500
		}

		r.JSON(status, map[string]string{"error": err.Error()})
		return
	}
	r.JSON(200, result)
}
开发者ID:h12w,项目名称:golang-rest-server,代码行数:26,代码来源:handlers.go


注:本文中的labix/org/v2/mgo.Database类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。