我想为我的查询编写视图,但我发现没有为此定义函数。
自 MongoDB v3.4 起,支持从现有集合或其他视图创建 只读 视图。
为了创建视图,你可以执行create()数据库命令。例如:
db.runCommand( { create: <view>,
viewOn: <source>,
pipeline: <pipeline>,
collation: <collation>
} );
例如,如果你有一个来自 mongo shell 的create 查看命令,如下所示:
db.runCommand( {create:"testview",
viewOn: "collectionName",
pipeline: [ {"$project":{ "fieldA":1 } } ]
});
使用mongo-go-driver(当前版本为0.0.9),上面的创建视图命令可以用Go编写如下:
_, 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),),
),
),
),
)