mgo中使用pipeline/lookup

mgo中使用pipeline和lookup

1. Aggregation Pipeline

mongodb 3.2以后支持 Aggregation Pipeline, Aggregation Pipeline Quick Reference

$lookup Performs a left outer join to another collection in the same database to filter in documents from the “joined” collection for processing.

{
   $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
}

From: $lookup (aggregation)

其中的lookup功能可以实现类似于mysql中的join操作,方便于关联查询。

2. mgo中的实现外键关联

// See also
// https://docs.mongodb.com/manual/aggregation/
// https://docs.mongodb.com/manual/core/aggregation-pipeline/
// https://github.com/go-mgo/mgo/issues/248

package main

import (
    "time"

    "fmt"

    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
)

type SuiteGroup struct {
    ID      *bson.ObjectId `bson:"_id,omitempty" json:"_id"`
    Name    *string        `bson:"name,omitempty" json:"name,omitempty"`
    SuiteID *bson.ObjectId `bson:"_suiteId" json:"_suiteId"`
    Kind    *string        `bson:"kind,omitempty" json:"kind,omitempty"`

    // pipeline get, Suites []Suite
    Suite []Suite `bson:"suite" json:"suites"`
}

type Suite struct {
    ID      *bson.ObjectId `bson:"_id" json:"_id,omitempty"`
    Created *time.Time     `bson:"created,omitempty" json:"created,omitempty"`
}


func main() {
    session, err := mgo.Dial("127.0.0.1")
    if err != nil {
        panic(err)
    }

    defer session.Close()

    // Optional. Switch the session to a monotonic behavior.
    session.SetMode(mgo.Monotonic, true)

    c := session.DB("test").C("suitegroups")

    pipeline := []bson.M{
        bson.M{"$match": bson.M{"name": "Admin"}},
        bson.M{"$lookup": bson.M{"from": "suites", "localField": "_suiteId", "foreignField": "_id", "as": "suite"}},
    }

    var resp SuiteGroup
    c.Pipe(pipeline).One(&resp)

    fmt.Printf("SuiteID [%s] SuiteObj %#v\n", resp.SuiteID.String(), resp.Suite[0])
}

gist

3. 参考

  1. Mongodb Aggregation
  2. Mongodb Aggregation Pipeline
  3. Aggregation Pipeline Quick Reference
  4. mgo pipelin issue248

mgo中使用pipeline/lookup》上有1条评论

  1. Pingback引用通告: Golang Mgo笔记 | 程序印象

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注