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),),
),
),
),
)