當前位置: 首頁>>代碼示例>>Golang>>正文


Golang mgo.Collection類代碼示例

本文整理匯總了Golang中labix/org/v2/mgo.Collection的典型用法代碼示例。如果您正苦於以下問題:Golang Collection類的具體用法?Golang Collection怎麽用?Golang Collection使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了Collection類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: getwords

// getwords reads the words from the database into a local variable stored on the heap.
// This cuts down on database accesses, and encapsulates the database interactions,
// making the random word selection more portable.
func getwords(localwords []string, words *mgo.Collection) error {
	// Within the words collection, Find documents with the word field, and then Select only
	// the contents of that field, and return an Iterator.
	iter := words.Find(bson.M{wordField: bson.M{"$exists": true}}).Select(bson.M{wordField: 1}).Limit(10000).Iter()

	// Iterate through the results pulling out the strings.
	tempresult := Word{}
	for i := 0; iter.Next(&tempresult); i++ {
		localwords[i] = tempresult.Word
		//Debug: fmt.Print(tempresult.Word, ",")
	}

	/* // Debug
	   //fmt.Println("First: ", localwords[0])
	   //fmt.Println("Last: ", localwords[10000-1])

	   //Debug: fmt.Println(len(localwords))
	*/

	// We should check len(localwords) to catch errors
	if len(localwords) < 1000 {
		// some error - we need to close the iterator also.
		// composite errors may occur.
	}
	// Close the iterator, return an error where applicable.
	if err := iter.Close(); err != nil {
		return err
	}
	return nil
}
開發者ID:voutasaurus,項目名稱:metamark,代碼行數:33,代碼來源:words.go

示例2: loadApplications

// loadApplications is a helper function which loads applications from the
// passed mongo collection and registers them as backends with the passed proxy
// mux.
func loadApplications(c *mgo.Collection, mux *triemux.Mux) (apps map[string]http.Handler) {
	app := &Application{}
	apps = make(map[string]http.Handler)

	iter := c.Find(nil).Iter()

	for iter.Next(&app) {
		backendUrl, err := url.Parse(app.BackendURL)
		if err != nil {
			log.Printf("router: couldn't parse URL %s for backend %s "+
				"(error: %v), skipping!", app.BackendURL, app.ApplicationId, err)
			continue
		}

		proxy := httputil.NewSingleHostReverseProxy(backendUrl)
		// Allow the proxy to keep more than the default (2) keepalive connections
		// per upstream.
		proxy.Transport = &http.Transport{MaxIdleConnsPerHost: 20}

		apps[app.ApplicationId] = proxy
	}

	if err := iter.Err(); err != nil {
		panic(err)
	}

	return
}
開發者ID:nickstenning,項目名稱:router-archive,代碼行數:31,代碼來源:router.go

示例3: confirmChecksum

func (a *Asset) confirmChecksum(coll *mgo.Collection, finished chan int) {
	defer func() { finished <- 1 }()

	fmt.Printf("Checking %s\n", a.Url)

	activeRequests <- 1
	resp, err := http.Get(a.Url)
	<-activeRequests

	if err != nil {
		fmt.Printf("Got HTTP Error for %s.  Error: %v\n", a.Url, err)
		return
	}

	newHasher := md5.New()
	io.Copy(newHasher, resp.Body)
	newHash := hex.EncodeToString(newHasher.Sum(nil))

	if newHash != a.Checksum {
		fmt.Printf("Hashes did not match: %s != %s\n", newHash, a.Checksum)
		a.Checksum = newHash
		err = coll.Update(bson.M{"_id": a.Id}, a)
		if err != nil {
			fmt.Printf("Error updating hash, got error %v\n", err)
		}
	} else {
		fmt.Printf("Hashes Matched!\n")
	}

}
開發者ID:josephwegner,項目名稱:canary,代碼行數:30,代碼來源:main.go

示例4: AddUser

func AddUser(collection *mgo.Collection, name, username, password string) {
	// Index
	index := mgo.Index{
		Key:        []string{"username", "email"},
		Unique:     true,
		DropDups:   true,
		Background: true,
		Sparse:     true,
	}

	err := collection.EnsureIndex(index)
	if err != nil {
		panic(err)
	}

	bcryptPassword, _ := bcrypt.GenerateFromPassword(
		[]byte(password), bcrypt.DefaultCost)

	// Insert Dataz
	err = collection.Insert(&models.User{Name: name, Username: username, Password: bcryptPassword})

	if err != nil {
		panic(err)
	}
}
開發者ID:netsharec,項目名稱:ironzebra,代碼行數:25,代碼來源:user.go

示例5: ListByQWithFields

// 查詢某些字段, q是查詢條件, fields是字段名列表
func ListByQWithFields(collection *mgo.Collection, q bson.M, fields []string, i interface{}) {
	selector := make(bson.M, len(fields))
	for _, field := range fields {
		selector[field] = true
	}
	collection.Find(q).Select(selector).All(i)
}
開發者ID:kevinhuo88888,項目名稱:leanote,代碼行數:8,代碼來源:Mgo.go

示例6: idempotentRecordChapter

func idempotentRecordChapter(bid interface{}, chapter Chapter, col *mgo.Collection) interface{} {
	them := col.Find(bson.M{
		"position": chapter.Position,
		"book":     bid,
	}).Limit(1)
	cpt, e := them.Count()
	if e != nil {
		panic(e)
	}
	if cpt > 0 {
		ans := make(map[string]interface{})
		e = them.One(ans)
		if e != nil {
			panic(e)
		}
		return ans["_id"]
	}
	e = col.Insert(bson.M{
		"position": chapter.Position,
		"book":     bid,
	})
	if e != nil {
		panic(e)
	}
	return idempotentRecordChapter(bid, chapter, col)
}
開發者ID:revence27,項目名稱:Rhema,代碼行數:26,代碼來源:transfer.go

示例7: checkIdConflict

func checkIdConflict(w http.ResponseWriter, statementsC *mgo.Collection, statement Statement) int {

	if statement.Id != "" {
		// find any statements with this id
		var result Statement
		err := statementsC.Find(bson.M{"id": statement.Id}).One(&result)
		if err != nil {
			//fmt.Fprint(w, err)
			return 0
		}

		// kludge the result has "stored" so add field for comparison
		statement.Stored = result.Stored

		// can't compare structs with arrays/maps
		rj, _ := json.Marshal(result)
		sj, _ := json.Marshal(statement)

		if string(rj) != string(sj) {
			return http.StatusConflict
		} else {
			//same no need to insert
			return http.StatusNoContent
		}
	}
	return 0
}
開發者ID:DalianDragon,項目名稱:GO_LRS,代碼行數:27,代碼來源:LRSapi.go

示例8: GetAllRelevantSessions

func GetAllRelevantSessions(levelSessionsCollection *mgo.Collection) (topHumanSessions, topOgreSessions []lib.GameSession) {
	teams := [2]string{"humans", "ogres"}
	for _, teamName := range teams {
		queryParameters := bson.M{"level.original": "53558b5a9914f5a90d7ccddb", "submitted": true, "team": teamName}
		selection := bson.M{"team": 1, "totalScore": 1}
		sort := bson.M{"totalScore": -1}
		pipe := levelSessionsCollection.Pipe([]bson.M{{"$match": queryParameters}, {"$project": selection}, {"$sort": sort}, {"$limit": numberOfTopGamesToRank}})
		var err error
		var documentCount int
		if teamName == "humans" {
			err = pipe.All(&topHumanSessions)
			documentCount = len(topHumanSessions)
		} else {
			err = pipe.All(&topOgreSessions)
			documentCount = len(topOgreSessions)
		}

		if err != nil {
			panic(err)
		}
		fmt.Println("Retrieved", documentCount, teamName, "sessions!")
	}

	return topHumanSessions, topOgreSessions
}
開發者ID:schmatz,項目名稱:coco-verify,代碼行數:25,代碼來源:server.go

示例9: main

func main() {
	var (
		mongoSession *mgo.Session
		database     *mgo.Database
		collection   *mgo.Collection
		changeInfo   *mgo.ChangeInfo
		err          error
	)

	if mongoSession, err = mgo.Dial("localhost"); err != nil {
		panic(err)
	}

	database = mongoSession.DB("mgo_examples_03")
	collection = database.C("todos")

	// START OMIT
	var todo = Todo{
		Id:      bson.NewObjectId(),
		Task:    "Demo mgo",
		Created: time.Now(),
	}

	// This is a shortcut to collection.Upsert(bson.M{"_id": todo.id}, &todo)
	if changeInfo, err = collection.UpsertId(todo.Id, &todo); err != nil {
		panic(err)
	}
	// END OMIT

	fmt.Printf("Todo: %# v", pretty.Formatter(todo))
	fmt.Printf("Change Info: %# v", pretty.Formatter(changeInfo))

}
開發者ID:johnzan,項目名稱:talks,代碼行數:33,代碼來源:main.go

示例10: Count

func Count(collection *mgo.Collection, q interface{}) int {
	cnt, err := collection.Find(q).Count()
	if err != nil {
		Err(err)
	}
	return cnt
}
開發者ID:kevinhuo88888,項目名稱:leanote,代碼行數:7,代碼來源:Mgo.go

示例11: copyDirectoryDocument

func (fs *BFS) copyDirectoryDocument(d *Directory, newprefix, oldprefix, newname string, c *mgo.Collection) error {
	// update parent path prefix with new prefix
	_parent_path := d.Header.Parent
	_parent_path = strings.Replace(_parent_path, oldprefix, newprefix, 1)

	// update header info
	uuid, err := makeUUID()
	if err != nil {
		return err
	}

	nw := time.Now()
	dt := formatDatetime(&nw)
	id := fmt.Sprintf("%s:%s", uuid, dt)
	d.Header.Parent = _parent_path
	if newname != "" {
		err = fs.validateDirName(newname)
		if err != nil {
			return err
		}
		d.Header.Name = newname
	}
	d.Header.Created = dt
	d.Id = id
	// save to mongodb
	err = c.Insert(&d)
	if err != nil {
		return err
	}

	return nil
}
開發者ID:ballacky13,項目名稱:bytengine,代碼行數:32,代碼來源:bfs.go

示例12: DeleteIndex

// DeleteIndex deletes a collections index
func DeleteIndex(c *mgo.Collection) {
	defer dendtimer(starttimer())
	err := c.DropIndex("name")
	if err != nil {
		panic(err)
	}
}
開發者ID:klydel,項目名稱:random,代碼行數:8,代碼來源:mongotest.go

示例13: txPagingFunc

func txPagingFunc(c *mgo.Collection, first, last string, args ...interface{}) (query bson.M, err error) {
	tx := &Tx{}

	if bson.IsObjectIdHex(first) {
		if err := c.FindId(bson.ObjectIdHex(first)).One(tx); err != nil {
			return nil, err
		}
		query = bson.M{
			"time": bson.M{
				"$gte": tx.Time,
			},
		}
	} else if bson.IsObjectIdHex(last) {
		if err := c.FindId(bson.ObjectIdHex(last)).One(tx); err != nil {
			return nil, err
		}
		query = bson.M{
			"time": bson.M{
				"$lte": tx.Time,
			},
		}
	}

	return
}
開發者ID:shevilangle,項目名稱:sports,代碼行數:25,代碼來源:account.go

示例14: searchPagingFunc

func searchPagingFunc(c *mgo.Collection, first, last string, args ...interface{}) (query bson.M, err error) {
	user := &Account{}

	if len(first) > 0 {
		if err := c.FindId(first).One(user); err != nil {
			return nil, err
		}
		query = bson.M{
			"lastlogin": bson.M{
				"$gte": user.LastLogin,
			},
		}
	} else if len(last) > 0 {
		if err := c.FindId(last).One(user); err != nil {
			return nil, err
		}
		query = bson.M{
			"lastlogin": bson.M{
				"$lte": user.LastLogin,
			},
		}
	}

	return
}
開發者ID:shevilangle,項目名稱:sports,代碼行數:25,代碼來源:account.go

示例15: recordPagingFunc

func recordPagingFunc(c *mgo.Collection, first, last string, args ...interface{}) (query bson.M, err error) {
	record := &Record{}

	if bson.IsObjectIdHex(first) {
		if err := c.FindId(bson.ObjectIdHex(first)).One(record); err != nil {
			return nil, err
		}
		query = bson.M{
			"starttime": bson.M{
				"$gte": record.PubTime,
			},
		}
	} else if bson.IsObjectIdHex(last) {
		if err := c.FindId(bson.ObjectIdHex(last)).One(record); err != nil {
			return nil, err
		}
		query = bson.M{
			"starttime": bson.M{
				"$lte": record.PubTime,
			},
		}
	}

	return
}
開發者ID:shevilangle,項目名稱:sports,代碼行數:25,代碼來源:account.go


注:本文中的labix/org/v2/mgo.Collection類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。