How to create a view form multiple collections

26 views
Skip to first unread message

Tao Liu

unread,
Oct 24, 2019, 6:48:25 AM10/24/19
to mongodb-go-driver
Hi, 
     How can I create a view from multiple collections like this.


Thanks
Tao Liu

Wan Bachtiar

unread,
Oct 30, 2019, 7:09:58 AM10/30/19
to mongodb-go-driver

How can I create a view from multiple collections like this.

Hi Tao,

I’d assume that you already know how to create a view from multiple collections but wondering how to do so using MongoDB Go driver.

For all (or most) mongo shell methods such as db.createView() you can find the underlying database command and use RunCommand to execute the command. Below is an example code of RunCommand with views command:

db := client.Database("dbname")

pipeline := bson.A{
    bson.M{ 
        "$lookup": bson.M{ 
            "from": "targetColl", 
            "localField": "sourceField", 
            "foreignField": "targetField", 
            "as": "newField"},
}}

viewCommand := bson.M{"create": "newViewName", "viewOn": "sourceColl", "pipeline": pipeline }
result := db.RunCommand(context.Background(), viewCommand)

fmt.Println(result.DecodeBytes())

Regards,
Wan.

Reply all
Reply to author
Forward
0 new messages