mgo初探笔记

首先是通过Dial函数建立一个连接,这个Dial内部调用的是DialWithTimeOut,还带有默认的DailInfo这个结构体。

之后就是session.DB(DbName).C(CName)这样获得集合对应的结构体Collection。

Collection的find方法可以返回query结构体。

比如想要查找一个账号是否存在

    session, err := mgo.Dial(LocalAddress)
    if err != nil {
        panic(err)
    }
    defer session.Close()

    c := session.DB(DbName).C(SCName)

    err = c.Find(bson.M{"account": account}).One(&result)

if(err == ErrorNotFound){
  //如果错误是ErrorNotFound的话就代表该账号不存在
}
if(err!=nil){
//如果没有错误就代表查找到了该账号
}
  

 有条件的查询比如这样

bson.M{{"time": bson.M{ "$gt": t } }}

选择time大于某个时间的,而且mgo支持time类型,不要做什么特别的转换。

 

 来看看查询的方式

type Query
type Query struct {
    // contains filtered or unexported fields
}
func (*Query) All
func (q *Query) All(result interface{}) error
All works like Iter.All.

func (*Query) Apply
func (q *Query) Apply(change Change, result interface{}) (info *ChangeInfo, err error)
Apply runs the findAndModify MongoDB command, which allows updating, upserting or removing a document matching a query and atomically returning either the old version (the default) or the new version of the document (when ReturnNew is true). If no objects are found Apply returns ErrNotFound.

The Sort and Select query methods affect the result of Apply. In case multiple documents match the query, Sort enables selecting which document to act upon by ordering it first. Select enables retrieving only a selection of fields of the new or old document.

This simple example increments a counter and prints its new value:

change := mgo.Change{
        Update: bson.M{"$inc": bson.M{"n": 1}},
        ReturnNew: true,
}
info, err = col.Find(M{"_id": id}).Apply(change, &doc)
fmt.Println(doc.N)
This method depends on MongoDB >= 2.0 to work properly.

Relevant documentation:

http://www.mongodb.org/display/DOCS/findAndModify+Command
http://www.mongodb.org/display/DOCS/Updating
http://www.mongodb.org/display/DOCS/Atomic+Operations
func (*Query) Batch
func (q *Query) Batch(n int) *Query
Batch sets the batch size used when fetching documents from the database. It's possible to change this setting on a per-session basis as well, using the Batch method of Session.

The default batch size is defined by the database itself. As of this writing, MongoDB will use an initial size of min(100 docs, 4MB) on the first batch, and 4MB on remaining ones.

func (*Query) Count
func (q *Query) Count() (n int, err error)
Count returns the total number of documents in the result set.

func (*Query) Distinct
func (q *Query) Distinct(key string, result interface{}) error
Distinct returns a list of distinct values for the given key within the result set. The list of distinct values will be unmarshalled in the "values" key of the provided result parameter.

For example:

var result []int
err := collection.Find(bson.M{"gender": "F"}).Distinct("age", &result)
Relevant documentation:

http://www.mongodb.org/display/DOCS/Aggregation
func (*Query) Explain
func (q *Query) Explain(result interface{}) error
Explain returns a number of details about how the MongoDB server would execute the requested query, such as the number of objects examined, the number of time the read lock was yielded to allow writes to go in, and so on.

For example:

m := bson.M{}
err := collection.Find(bson.M{"filename": name}).Explain(m)
if err == nil {
    fmt.Printf("Explain: %#v\n", m)
}
Relevant documentation:

http://www.mongodb.org/display/DOCS/Optimization
http://www.mongodb.org/display/DOCS/Query+Optimizer
func (*Query) For
func (q *Query) For(result interface{}, f func() error) error
The For method is obsolete and will be removed in a future release. See Iter as an elegant replacement.

func (*Query) Hint
func (q *Query) Hint(indexKey ...string) *Query
Hint will include an explicit "hint" in the query to force the server to use a specified index, potentially improving performance in some situations. The provided parameters are the fields that compose the key of the index to be used. For details on how the indexKey may be built, see the EnsureIndex method.

For example:

query := collection.Find(bson.M{"firstname": "Joe", "lastname": "Winter"})
query.Hint("lastname", "firstname")
Relevant documentation:

http://www.mongodb.org/display/DOCS/Optimization
http://www.mongodb.org/display/DOCS/Query+Optimizer
func (*Query) Iter
func (q *Query) Iter() *Iter
Iter executes the query and returns an iterator capable of going over all the results. Results will be returned in batches of configurable size (see the Batch method) and more documents will be requested when a configurable number of documents is iterated over (see the Prefetch method).

func (*Query) Limit
func (q *Query) Limit(n int) *Query
Limit restricts the maximum number of documents retrieved to n, and also changes the batch size to the same value. Once n documents have been returned by Next, the following call will return ErrNotFound.

func (*Query) LogReplay
func (q *Query) LogReplay() *Query
LogReplay enables an option that optimizes queries that are typically made against the MongoDB oplog for replaying it. This is an internal implementation aspect and most likely uninteresting for other uses. It has seen at least one use case, though, so it's exposed via the API.

func (*Query) MapReduce
func (q *Query) MapReduce(job *MapReduce, result interface{}) (info *MapReduceInfo, err error)
MapReduce executes a map/reduce job for documents covered by the query. That kind of job is suitable for very flexible bulk aggregation of data performed at the server side via Javascript functions.

Results from the job may be returned as a result of the query itself through the result parameter in case they'll certainly fit in memory and in a single document. If there's the possibility that the amount of data might be too large, results must be stored back in an alternative collection or even a separate database, by setting the Out field of the provided MapReduce job. In that case, provide nil as the result parameter.

These are some of the ways to set Out:

nil
    Inline results into the result parameter.

bson.M{"replace": "mycollection"}
    The output will be inserted into a collection which replaces any
    existing collection with the same name.

bson.M{"merge": "mycollection"}
    This option will merge new data into the old output collection. In
    other words, if the same key exists in both the result set and the
    old collection, the new key will overwrite the old one.

bson.M{"reduce": "mycollection"}
    If documents exist for a given key in the result set and in the old
    collection, then a reduce operation (using the specified reduce
    function) will be performed on the two values and the result will be
    written to the output collection. If a finalize function was
    provided, this will be run after the reduce as well.

bson.M{...., "db": "mydb"}
    Any of the above options can have the "db" key included for doing
    the respective action in a separate database.
The following is a trivial example which will count the number of occurrences of a field named n on each document in a collection, and will return results inline:

job := &mgo.MapReduce{
        Map:      "function() { emit(this.n, 1) }",
        Reduce:   "function(key, values) { return Array.sum(values) }",
}
var result []struct { Id int "_id"; Value int }
_, err := collection.Find(nil).MapReduce(job, &result)
if err != nil {
    return err
}
for _, item := range result {
    fmt.Println(item.Value)
}
This function is compatible with MongoDB 1.7.4+.

Relevant documentation:

http://www.mongodb.org/display/DOCS/MapReduce
func (*Query) One
func (q *Query) One(result interface{}) (err error)
One executes the query and unmarshals the first obtained document into the result argument. The result must be a struct or map value capable of being unmarshalled into by gobson. This function blocks until either a result is available or an error happens. For example:

err := collection.Find(bson.M{"a", 1}).One(&result)
In case the resulting document includes a field named $err or errmsg, which are standard ways for MongoDB to return query errors, the returned err will be set to a *QueryError value including the Err message and the Code. In those cases, the result argument is still unmarshalled into with the received document so that any other custom values may be obtained if desired.

func (*Query) Prefetch
func (q *Query) Prefetch(p float64) *Query
Prefetch sets the point at which the next batch of results will be requested. When there are p*batch_size remaining documents cached in an Iter, the next batch will be requested in background. For instance, when using this:

query.Batch(200).Prefetch(0.25)
and there are only 50 documents cached in the Iter to be processed, the next batch of 200 will be requested. It's possible to change this setting on a per-session basis as well, using the SetPrefetch method of Session.

The default prefetch value is 0.25.

func (*Query) Select
func (q *Query) Select(selector interface{}) *Query
Select enables selecting which fields should be retrieved for the results found. For example, the following query would only retrieve the name field:

err := collection.Find(nil).Select(bson.M{"name": 1}).One(&result)
Relevant documentation:

http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields
func (*Query) Skip
func (q *Query) Skip(n int) *Query
Skip skips over the n initial documents from the query results. Note that this only makes sense with capped collections where documents are naturally ordered by insertion time, or with sorted results.

func (*Query) Snapshot
func (q *Query) Snapshot() *Query
Snapshot will force the performed query to make use of an available index on the _id field to prevent the same document from being returned more than once in a single iteration. This might happen without this setting in situations when the document changes in size and thus has to be moved while the iteration is running.

Because snapshot mode traverses the _id index, it may not be used with sorting or explicit hints. It also cannot use any other index for the query.

Even with snapshot mode, items inserted or deleted during the query may or may not be returned; that is, this mode is not a true point-in-time snapshot.

The same effect of Snapshot may be obtained by using any unique index on field(s) that will not be modified (best to use Hint explicitly too). A non-unique index (such as creation time) may be made unique by appending _id to the index when creating it.

Relevant documentation:

http://www.mongodb.org/display/DOCS/How+to+do+Snapshotted+Queries+in+the+Mongo+Database
func (*Query) Sort
func (q *Query) Sort(fields ...string) *Query
Sort asks the database to order returned documents according to the provided field names. A field name may be prefixed by - (minus) for it to be sorted in reverse order.

For example:

query1 := collection.Find(nil).Sort("firstname", "lastname")
query2 := collection.Find(nil).Sort("-age")
query3 := collection.Find(nil).Sort("$natural")
Relevant documentation:

http://www.mongodb.org/display/DOCS/Sorting+and+Natural+Order
func (*Query) Tail
func (q *Query) Tail(timeout time.Duration) *Iter
Tail returns a tailable iterator. Unlike a normal iterator, a tailable iterator may wait for new values to be inserted in the collection once the end of the current result set is reached, A tailable iterator may only be used with capped collections.

The timeout parameter indicates how long Next will block waiting for a result before timing out. If set to -1, Next will not timeout, and will continue waiting for a result for as long as the cursor is valid and the session is not closed. If set to 0, Next times out as soon as it reaches the end of the result set. Otherwise, Next will wait for at least the given number of seconds for a new document to be available before timing out.

On timeouts, Next will unblock and return false, and the Timeout method will return true if called. In these cases, Next may still be called again on the same iterator to check if a new value is available at the current cursor position, and again it will block according to the specified timeoutSecs. If the cursor becomes invalid, though, both Next and Timeout will return false and the query must be restarted.

The following example demonstrates timeout handling and query restarting:

iter := collection.Find(nil).Sort("$natural").Tail(5 * time.Second)
for {
     for iter.Next(&result) {
         fmt.Println(result.Id)
         lastId = result.Id
     }
     if err := iter.Close(); err != nil {
         return err
     }
     if iter.Timeout() {
         continue
     }
     query := collection.Find(bson.M{"_id": bson.M{"$gt": lastId}})
     iter = query.Sort("$natural").Tail(5 * time.Second)
}
Relevant documentation:

http://www.mongodb.org/display/DOCS/Tailable+Cursors
http://www.mongodb.org/display/DOCS/Capped+Collections
http://www.mongodb.org/display/DOCS/Sorting+and+Natural+Order

 

首先观察一下Collection这个类型.

type Collection
type Collection struct {
    Database *Database
    Name     string // "collection"
    FullName string // "db.collection"
}

func (*Collection) Count
func (c *Collection) Count() (n int, err error)

//返回document的总数

func (*Collection) Create
func (c *Collection) Create(info *CollectionInfo) error

Create explicitly creates the c collection with details of info. MongoDB creates collections automatically on use, so this method is only necessary when creating collection with non-default characteristics, such as capped collections.

//创建一个有具体info的集合,一般集合都自动创立了,所以这个方法只在需要非默认info的情况下才使用。

//相关内容
http://www.mongodb.org/display/DOCS/createCollection+Command
http://www.mongodb.org/display/DOCS/Capped+Collections


func (*Collection) DropCollection
func (c *Collection) DropCollection() error

//删除这个集合,和集合里的所有documents

func (*Collection) DropIndex
func (c *Collection) DropIndex(key ...string) error

//删除key的索引,key...表示参数不确定,传入的是一个slice

The key value determines which fields compose the index. The index ordering will be ascending by default. To obtain an index with a descending order, the field name should be prefixed by a dash (e.g. []string{"-time"}).

//索引默认是升序的,如果不想按升序来的话,字符串前面加个破折号,比如“-lastname”

//例子
err := collection.DropIndex("lastname", "firstname")


func (*Collection) EnsureIndex
func (c *Collection) EnsureIndex(index Index) error

EnsureIndex ensures an index with the given key exists, creating it with the provided parameters if necessary.

Once EnsureIndex returns successfully, following requests for the same index will not contact the server unless Collection.DropIndex is used to drop the same index, or Session.ResetIndexCache is called.

//用index建立索引,index的例子如下
index := Index{
    Key: []string{"lastname", "firstname"},
    Unique: true,
    DropDups: true,
    Background: true, // See notes.
    Sparse: true,
}
err := collection.EnsureIndex(index)


The Key value determines which fields compose the index. The index ordering will be ascending by default. To obtain an index with a descending order, the field name should be prefixed by a dash (e.g. []string{"-time"}).

//索引默认是升序的,如果不想按升序来的话,字符串前面加个破折号,比如“-lastname”

If Unique is true, the index must necessarily contain only a single document per Key. With DropDups set to true, documents with the same key as a previously indexed one will be dropped rather than an error returned.

//Uniqe设置成true,没个document只能有一个索引,DropDups设置成true,如果有文档的索引和之前的存在一样就会被删除,而不是报错

If Background is true, other connections will be allowed to proceed using the collection without the index while it's being built. Note that the session executing EnsureIndex will be blocked for as long as it takes for the index to be built.

//background设置为true的话,其他的连接可以访问集合,即使索引还没有建立,但是建立索引的连接是阻塞的,直到索引被建立完。

If Sparse is true, only documents containing the provided Key fields will be included in the index. When using a sparse index for sorting, only indexed documents will be returned.

If ExpireAfter is non-zero, the server will periodically scan the collection and remove documents containing an indexed time.Time field with a value older than ExpireAfter. See the documentation for details:
http://docs.mongodb.org/manual/tutorial/expire-data


Other kinds of indexes are also supported through that API. Here is an example:
index := Index{
    Key: []string{"$2d:loc"},
    Bits: 26,
}
err := collection.EnsureIndex(index)


The example above requests the creation of a "2d" index for the "loc" field.

The 2D index bounds may be changed using the Min and Max attributes of the Index value. The default bound setting of (-180, 180) is suitable for latitude/longitude pairs.

The Bits parameter sets the precision of the 2D geohash values. If not provided, 26 bits are used, which is roughly equivalent to 1 foot of precision for the default (-180, 180) index bounds.

Relevant documentation:
http://www.mongodb.org/display/DOCS/Indexes
http://www.mongodb.org/display/DOCS/Indexing+Advice+and+FAQ
http://www.mongodb.org/display/DOCS/Indexing+as+a+Background+Operation
http://www.mongodb.org/display/DOCS/Geospatial+Indexing
http://www.mongodb.org/display/DOCS/Multikeys


func (*Collection) EnsureIndexKey
func (c *Collection) EnsureIndexKey(key ...string) error

EnsureIndexKey ensures an index with the given key exists, creating it if necessary.

This example:
err := collection.EnsureIndexKey("a", "b")


Is equivalent to:
err := collection.EnsureIndex(mgo.Index{Key: []string{"a", "b"}})


See the EnsureIndex method for more details.

func (*Collection) Find
func (c *Collection) Find(query interface{}) *Query

Find prepares a query using the provided document. The document may be a map or a struct value capable of being marshalled with bson. The map may be a generic one using interface{} for its key and/or values, such as bson.M, or it may be a properly typed map. Providing nil as the document is equivalent to providing an empty document such as bson.M{}.

Further details of the query may be tweaked using the resulting Query value, and then executed to retrieve results using methods such as One, For, Iter, or Tail.

In case the resulting document includes a field named $err or errmsg, which are standard ways for MongoDB to return query errors, the returned err will be set to a *QueryError value including the Err message and the Code. In those cases, the result argument is still unmarshalled into with the received document so that any other custom values may be obtained if desired.

find的语法参考官方网站:
http://www.mongodb.org/display/DOCS/Querying
http://www.mongodb.org/display/DOCS/Advanced+Queries


func (*Collection) FindId
func (c *Collection) FindId(id interface{}) *Query
/相当于
query := collection.Find(bson.M{"_id": id})


func (*Collection) Indexes
func (c *Collection) Indexes() (indexes []Index, err error)

Indexes returns a list of all indexes for the collection.

For example, this snippet would drop all available indexes:
indexes, err := collection.Indexes()
if err != nil {
    return err
}
for _, index := range indexes {
    err = collection.DropIndex(index.Key...)
    if err != nil {
        return err
    }
}


See the EnsureIndex method for more details on indexes.

func (*Collection) Insert
func (c *Collection) Insert(docs ...interface{}) error

Insert inserts one or more documents in the respective collection. In case the session is in safe mode (see the SetSafe method) and an error happens while inserting the provided documents, the returned error will be of type *LastError.

func (*Collection) Pipe
func (c *Collection) Pipe(pipeline interface{}) *Pipe

Pipe prepares a pipeline to aggregate. The pipeline document must be a slice built in terms of the aggregation framework language.

For example:
pipe := collection.Pipe([]bson.M{{"$match": bson.M{"name": "Otavio"}}})
iter := pipe.Iter()


Relevant documentation:
http://docs.mongodb.org/manual/reference/aggregation
http://docs.mongodb.org/manual/applications/aggregation
http://docs.mongodb.org/manual/tutorial/aggregation-examples


func (*Collection) Remove
func (c *Collection) Remove(selector interface{}) error

Remove finds a single document matching the provided selector document and removes it from the database. If the session is in safe mode (see SetSafe) a ErrNotFound error is returned if a document isn't found, or a value of type *LastError when some other error is detected.

Relevant documentation:
http://www.mongodb.org/display/DOCS/Removing


func (*Collection) RemoveAll
func (c *Collection) RemoveAll(selector interface{}) (info *ChangeInfo, err error)

RemoveAll finds all documents matching the provided selector document and removes them from the database. In case the session is in safe mode (see the SetSafe method) and an error happens when attempting the change, the returned error will be of type *LastError.

Relevant documentation:
http://www.mongodb.org/display/DOCS/Removing


func (*Collection) RemoveId
func (c *Collection) RemoveId(id interface{}) error

RemoveId is a convenience helper equivalent to:
err := collection.Remove(bson.M{"_id": id})


See the Remove method for more details.

func (*Collection) Update
func (c *Collection) Update(selector interface{}, change interface{}) error

Update finds a single document matching the provided selector document and modifies it according to the change document. If the session is in safe mode (see SetSafe) a ErrNotFound error is returned if a document isn't found, or a value of type *LastError when some other error is detected.

Relevant documentation:
http://www.mongodb.org/display/DOCS/Updating
http://www.mongodb.org/display/DOCS/Atomic+Operations


func (*Collection) UpdateAll
func (c *Collection) UpdateAll(selector interface{}, change interface{}) (info *ChangeInfo, err error)

UpdateAll finds all documents matching the provided selector document and modifies them according to the change document. If the session is in safe mode (see SetSafe) details of the executed operation are returned in info or an error of type *LastError when some problem is detected. It is not an error for the update to not be applied on any documents because the selector doesn't match.

Relevant documentation:
http://www.mongodb.org/display/DOCS/Updating
http://www.mongodb.org/display/DOCS/Atomic+Operations


func (*Collection) UpdateId
func (c *Collection) UpdateId(id interface{}, change interface{}) error

UpdateId is a convenience helper equivalent to:
err := collection.Update(bson.M{"_id": id}, change)


See the Update method for more details.

func (*Collection) Upsert
func (c *Collection) Upsert(selector interface{}, change interface{}) (info *ChangeInfo, err error)

Upsert finds a single document matching the provided selector document and modifies it according to the change document. If no document matching the selector is found, the change document is applied to the selector document and the result is inserted in the collection. If the session is in safe mode (see SetSafe) details of the executed operation are returned in info, or an error of type *LastError when some problem is detected.

//没有找到就直接插入

Relevant documentation:
http://www.mongodb.org/display/DOCS/Updating
http://www.mongodb.org/display/DOCS/Atomic+Operations


func (*Collection) UpsertId
func (c *Collection) UpsertId(id interface{}, change interface{}) (info *ChangeInfo, err error)

UpsertId is a convenience helper equivalent to:
info, err := collection.Upsert(bson.M{"_id": id}, change)


See the Upsert method for more details.

func (*Collection) With
func (c *Collection) With(s *Session) *Collection

With returns a copy of c that uses session s.

type CollectionInfo
type CollectionInfo struct {
    // DisableIdIndex prevents the automatic creation of the index
    // on the _id field for the collection.
    DisableIdIndex bool

    // ForceIdIndex enforces the automatic creation of the index
    // on the _id field for the collection. Capped collections,
    // for example, do not have such an index by default.
    ForceIdIndex bool

    // If Capped is true new documents will replace old ones when
    // the collection is full. MaxBytes must necessarily be set
    // to define the size when the collection wraps around.
    // MaxDocs optionally defines the number of documents when it
    // wraps, but MaxBytes still needs to be set.
    Capped   bool
    MaxBytes int
    MaxDocs  int
}

The CollectionInfo type holds metadata about a collection.

Relevant documentation:
http://www.mongodb.org/display/DOCS/createCollection+Command
http://www.mongodb.org/display/DOCS/Capped+Collections

 

posted @ 2014-01-03 12:52  ggaaooppeenngg  阅读(5942)  评论(0编辑  收藏  举报