普通网友 2018-07-14 07:03
浏览 140

如何使用Go的mongo驱动程序在Mongodb查询上创建视图?

I am working with Golang and Mongodb. I am using https://godoc.org/gopkg.in/mgo.v2 mongo driver for Go. I want to write views on my queries but I found that there is no function defined for that. Mongo Views is a recent feature provided in version 3.4. I have checked it in other driver also:

https://godoc.org/github.com/mongodb/mongo-go-driver/mongo

Its not even there. How can I get this feature in my driver ?

  • 写回答

1条回答 默认 最新

  • doufengsui7449 2018-07-19 05:07
    关注

    I want to write views on my queries but I found that there is no function defined for that.

    Since MongoDB v3.4, there's a support for creating read-only views from existing collections or other views.

    In order to create a view, you can execute create() database command. For example:

    db.runCommand( { create: <view>, 
                     viewOn: <source>, 
                     pipeline: <pipeline>, 
                     collation: <collation> 
    } );
    

    For example if you have a create view command from mongo shell as below:

    db.runCommand( {create:"testview", 
                    viewOn: "collectionName", 
                    pipeline: [ {"$project":{ "fieldA":1 } } ] 
    });
    

    Utilising mongo-go-driver (currently version 0.0.9), the above create view command can be written in Go as below:

    _, err = database.RunCommand(
        context.Background(),
        bson.NewDocument(bson.EC.String("create", "testview"),
                         bson.EC.String("viewOn", "collectionName"),
                         bson.EC.ArrayFromElements(
                             "pipeline", bson.VC.DocumentFromElements(
                                 bson.EC.SubDocumentFromElements(
                                     "$project", bson.EC.Int32("fieldA", 1),),
                                 ),
                             ),
                         ),
    )
    
    评论

报告相同问题?

悬赏问题

  • ¥20 蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏