mo

package module
v0.0.0-...-964f350 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 17, 2023 License: Apache-2.0 Imports: 15 Imported by: 0

README


goclub/mongo

mongo 手册中文版 + go 语言实现

在线文档地址: https://mongo.goclub.run/

开发

环境

本地mongo环境可以使用 goclub/docker 快速创建

编写文档

# 确保你安装了 jekyll
bundle exec jekyll serve

migrate.go

Documentation

Index

Examples

Constants

View Source
const ExampleReplicaSetURI = "mongodb://goclub:goclub@localhost:27017/?authSource=goclub&readPreference=primary&directConnection=true&ssl=false"

演示用连接uri,正式项目请使用公司环境对于的uri,因为示例的副本集环境是docker所以需要使用connect=direct

Variables

View Source
var Logger = log.Default()

Functions

func Migrate

func Migrate(db *Database, ptr interface{})
Example

In a formal project you should use `go run cmd/migrate/main.go`, not running in init function

package main

import (
	"context"

	xerr "github.com/goclub/error"

	mo "github.com/goclub/mongo"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"

	mongoOptions "go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
)

var db *mo.Database
var commentColl *mo.Collection
var newsStatDailyColl *mo.Collection
var locationCool *mo.Collection

func init() {
	ExampleNewDatabase()
	ExampleNewCollection()
	ExampleMigrate()
}
func ExampleNewDatabase() {
	ctx := context.Background()
	client, err := mongo.Connect(ctx, mongoOptions.Client().ApplyURI(mo.ExampleReplicaSetURI))
	if err != nil {
		panic(err)
	}
	err = client.Ping(ctx, readpref.Primary())
	if err != nil {
		panic(err)
	}
	db = mo.NewDatabase(client, "goclub")
}
func ExampleNewCollection() {
	var err error
	defer func() {
		if err != nil {
			xerr.PrintStack(err)
		}
	}()
	commentColl = mo.NewCollection(db, "exampleComment")
	newsStatDailyColl = mo.NewCollection(db, "exampleNewsStatDaily")
	locationCool = mo.NewCollection(db, "exampleLocation")
}

type MigrateActions struct {
}

func (MigrateActions) Migrate_2021_11_23__09_52_CreateExmapleCommentJSONSchema(db *mo.Database) (err error) {
	f := mo.ExampleComment{}.Field()
	var jsonSchema = bson.M{
		"bsonType":             "object",
		"additionalProperties": false,
		"properties": bson.M{
			f.ID: bson.M{
				"bsonType": "objectId",
			},
			f.UserID: bson.M{
				"bsonType": "number",
			},
			f.NewsID: bson.M{
				"bsonType": "objectId",
			},
			f.Message: bson.M{
				"bsonType": "string",
			},
			f.Like: bson.M{
				"bsonType": "number",
			},
		},
	}
	var validator = bson.M{
		"$jsonSchema": jsonSchema,
	}
	opts := mongoOptions.CreateCollection().SetValidator(validator)
	err = db.Core.CreateCollection(context.TODO(), "exampleComment", opts)
	if err != nil {
		return
	}
	return
}
func (MigrateActions) Migrate_2021_11_23__09_52_CreateExampleNewsStatDailyIndexs(db *mo.Database) (err error) {

	f := mo.ExampleNewsStatDaily{}.Field()
	_, err = newsStatDailyColl.Core.Indexes().CreateOne(context.TODO(), mongo.IndexModel{
		Keys:    bson.D{{f.Date, 1}, {f.NewsID, 1}},
		Options: mongoOptions.Index().SetUnique(true),
	})
	if err != nil {
		return
	}
	return
}

// In a formal project you should use `go run cmd/migrate/main.go`, not running in init function
func ExampleMigrate() {
	mo.Migrate(db, &MigrateActions{})
}
func main() {
	mo.Migrate(db, &MigrateActions{})
}
Output:

func ProjectByStructTag

func ProjectByStructTag(v interface{}) bson.M

Types

type Action

type Action struct {
	ID   primitive.ObjectID `bson:"_id,omitempty"`
	Name string             `bson:"name"`
	Time time.Time          `bson:"time"`
	DefaultLifeCycle
}

goclub_mongo_migrate_action

func (*Action) AfterInsert

func (v *Action) AfterInsert(result ResultInsertOne) (err error)

type AggregateCommand

type AggregateCommand struct {
	LookupQuery  bool
	LookupResult bool
	// If true, the operation can write to temporary files in the _tmp subdirectory of the database directory path on
	// the server. The default value is false.
	AllowDiskUse xtype.OptionBool

	// The maximum number of documents to be included in each batch returned by the server.
	BatchSize xtype.OptionInt32

	// If true, writes executed as part of the operation will opt out of document-level validation on the server. This
	// option is valid for MongoDB versions >= 3.2 and is ignored for previous server versions. The default value is
	// false. See https://docs.mongodb.com/manual/core/schema-validation/ for more information about document
	// validation.
	BypassDocumentValidation xtype.OptionBool

	// Specifies a collation to use for string comparisons during the operation. This option is only valid for MongoDB
	// versions >= 3.4. For previous server versions, the driver will return an error if this option is used. The
	// default value is nil, which means the default collation of the collection will be used.
	Collation *options.Collation

	// The maximum amount of time that the query can run on the server. The default value is nil, meaning that there
	// is no time limit for query execution.
	MaxTime xtype.OptionDuration

	// The maximum amount of time that the server should wait for new documents to satisfy a tailable cursor query.
	// This option is only valid for MongoDB versions >= 3.2 and is ignored for previous server versions.
	MaxAwaitTime xtype.OptionDuration

	// A string that will be included in server logs, profiling logs, and currentOp queries to help trace the operation.
	// The default is the empty string, which means that no comment will be included in the logs.
	Comment xtype.OptionString

	// The index to use for the aggregation. This should either be the index name as a string or the index specification
	// as a document. The hint does not apply to $lookup and $graphLookup aggregation stages. The driver will return an
	// error if the hint parameter is a multi-key map. The default value is nil, which means that no hint will be sent.
	Hint interface{}

	// Specifies parameters for the aggregate expression. This option is only valid for MongoDB versions >= 5.0. Older
	// servers will report an error for using this option. This must be a document mapping parameter names to values.
	// Values must be constant or closed expressions that do not reference document fields. Parameters can then be
	// accessed as variables in an aggregate expression context (e.g. "$$var").
	Let interface{}
}

func (AggregateCommand) Options

func (c AggregateCommand) Options() (opt []*options.AggregateOptions)

type Collection

type Collection struct {
	Core *mongo.Collection
	// contains filtered or unexported fields
}

func NewCollection

func NewCollection(db *Database, collectionName string, opts ...*options.CollectionOptions) *Collection
Example
package main

import (
	xerr "github.com/goclub/error"

	mo "github.com/goclub/mongo"
)

var db *mo.Database
var commentColl *mo.Collection
var newsStatDailyColl *mo.Collection
var locationCool *mo.Collection

func main() {
	/* In a formal environment ignore defer code */ var err error
	defer func() {
		if err != nil {
			xerr.PrintStack(err)
		}
	}()
	commentColl = mo.NewCollection(db, "exampleComment")
	newsStatDailyColl = mo.NewCollection(db, "exampleNewsStatDaily")
	locationCool = mo.NewCollection(db, "exampleLocation")
}
Output:

func (*Collection) Aggregate

func (c *Collection) Aggregate(ctx context.Context, pipeline interface{}, cmd AggregateCommand, resultPtr interface{}) (err error)

func (*Collection) AggregateCursor

func (c *Collection) AggregateCursor(ctx context.Context, pipeline interface{}, cmd AggregateCommand) (cursor *mongo.Cursor, err error)

func (*Collection) Count

func (c *Collection) Count(ctx context.Context, filter interface{}, cmd CountCommand) (total uint64, err error)

func (*Collection) DeleteMany

func (c *Collection) DeleteMany(ctx context.Context, filter interface{}, cmd DeleteCommand) (result *mongo.DeleteResult, err error)

func (*Collection) DeleteOne

func (c *Collection) DeleteOne(ctx context.Context, filter interface{}, cmd DeleteCommand) (result *mongo.DeleteResult, err error)

func (*Collection) Find

func (c *Collection) Find(ctx context.Context, filter interface{}, slicePtr interface{}, cmd FindCommand) (err error)
Example
package main

import (
	"context"

	xerr "github.com/goclub/error"

	mo "github.com/goclub/mongo"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"

	mongoOptions "go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
	"log"
)

var db *mo.Database
var commentColl *mo.Collection
var newsStatDailyColl *mo.Collection
var locationCool *mo.Collection

func init() {
	ExampleNewDatabase()
	ExampleNewCollection()
	ExampleMigrate()
}
func ExampleNewDatabase() {
	ctx := context.Background()
	client, err := mongo.Connect(ctx, mongoOptions.Client().ApplyURI(mo.ExampleReplicaSetURI))
	if err != nil {
		panic(err)
	}
	err = client.Ping(ctx, readpref.Primary())
	if err != nil {
		panic(err)
	}
	db = mo.NewDatabase(client, "goclub")
}
func ExampleNewCollection() {
	var err error
	defer func() {
		if err != nil {
			xerr.PrintStack(err)
		}
	}()
	commentColl = mo.NewCollection(db, "exampleComment")
	newsStatDailyColl = mo.NewCollection(db, "exampleNewsStatDaily")
	locationCool = mo.NewCollection(db, "exampleLocation")
}

type MigrateActions struct {
}

func (MigrateActions) Migrate_2021_11_23__09_52_CreateExmapleCommentJSONSchema(db *mo.Database) (err error) {
	f := mo.ExampleComment{}.Field()
	var jsonSchema = bson.M{
		"bsonType":             "object",
		"additionalProperties": false,
		"properties": bson.M{
			f.ID: bson.M{
				"bsonType": "objectId",
			},
			f.UserID: bson.M{
				"bsonType": "number",
			},
			f.NewsID: bson.M{
				"bsonType": "objectId",
			},
			f.Message: bson.M{
				"bsonType": "string",
			},
			f.Like: bson.M{
				"bsonType": "number",
			},
		},
	}
	var validator = bson.M{
		"$jsonSchema": jsonSchema,
	}
	opts := mongoOptions.CreateCollection().SetValidator(validator)
	err = db.Core.CreateCollection(context.TODO(), "exampleComment", opts)
	if err != nil {
		return
	}
	return
}
func (MigrateActions) Migrate_2021_11_23__09_52_CreateExampleNewsStatDailyIndexs(db *mo.Database) (err error) {

	f := mo.ExampleNewsStatDaily{}.Field()
	_, err = newsStatDailyColl.Core.Indexes().CreateOne(context.TODO(), mongo.IndexModel{
		Keys:    bson.D{{f.Date, 1}, {f.NewsID, 1}},
		Options: mongoOptions.Index().SetUnique(true),
	})
	if err != nil {
		return
	}
	return
}

// In a formal project you should use `go run cmd/migrate/main.go`, not running in init function
func ExampleMigrate() {
	mo.Migrate(db, &MigrateActions{})
}

func main() {
	/* In a formal environment ignore defer code */ var err error
	defer func() {
		if err != nil {
			xerr.PrintStack(err)
		}
	}()
	ctx := context.Background()
	// FindOneByObjectID
	{
		ExampleComment := mo.ExampleComment{
			UserID:  1,
			NewsID:  primitive.NewObjectID(),
			Message: "test find",
		}
		_, err = commentColl.InsertOne(ctx, &ExampleComment, mo.InsertOneCommand{})
		if err != nil {
			return
		}
		findExampleComment := mo.ExampleComment{}
		// ExampleComment.AliasObjectID = primitive.NewObjectID() // if unExampleComment this line of code, hasExampleComment will be false
		hasExampleComment, err := commentColl.FindOneByObjectID(ctx, ExampleComment.ID, &findExampleComment, mo.FindOneCommand{})
		if err != nil {
			return
		}
		log.Print("ExampleCollection_Find FindOneByObjectID: ", findExampleComment, hasExampleComment)
	}
	// FindOne
	{
		exampleCommentList := mo.ManyExampleComment{
			{UserID: 2, Message: "x", NewsID: primitive.NewObjectID()},
			{UserID: 2, Message: "y", NewsID: primitive.NewObjectID()},
		}
		_, err = commentColl.InsertMany(ctx, &exampleCommentList, mo.InsertManyCommand{})
		if err != nil {
			return
		}
		exampleComment := mo.ExampleComment{}
		field := exampleComment.Field()
		has, err := commentColl.FindOne(ctx, bson.D{
			{field.UserID, 2},
		}, &exampleComment, mo.FindOneCommand{
			LookupQuery:  true,
			LookupResult: true,
		})
		if err != nil {
			return
		}
		log.Print("ExampleCollection_Find FindOne: ", has, exampleComment)
	}
}
Output:

func (*Collection) FindCursor

func (c *Collection) FindCursor(ctx context.Context, filter interface{}, cmd FindCommand) (cursor *mongo.Cursor, err error)

func (*Collection) FindOne

func (c *Collection) FindOne(ctx context.Context, filter interface{}, ptr interface{}, cmd FindOneCommand) (has bool, err error)

func (*Collection) FindOneByObjectID

func (c *Collection) FindOneByObjectID(ctx context.Context, objectID primitive.ObjectID, ptr interface{}, cmd FindOneCommand) (has bool, err error)

func (*Collection) InsertMany

func (c *Collection) InsertMany(ctx context.Context, documents ManyDocument, cmd InsertManyCommand) (result ResultInsertMany, err error)
Example
package main

import (
	"context"

	xerr "github.com/goclub/error"

	mo "github.com/goclub/mongo"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"

	mongoOptions "go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
	"log"
)

var db *mo.Database
var commentColl *mo.Collection
var newsStatDailyColl *mo.Collection
var locationCool *mo.Collection

func init() {
	ExampleNewDatabase()
	ExampleNewCollection()
	ExampleMigrate()
}
func ExampleNewDatabase() {
	ctx := context.Background()
	client, err := mongo.Connect(ctx, mongoOptions.Client().ApplyURI(mo.ExampleReplicaSetURI))
	if err != nil {
		panic(err)
	}
	err = client.Ping(ctx, readpref.Primary())
	if err != nil {
		panic(err)
	}
	db = mo.NewDatabase(client, "goclub")
}
func ExampleNewCollection() {
	var err error
	defer func() {
		if err != nil {
			xerr.PrintStack(err)
		}
	}()
	commentColl = mo.NewCollection(db, "exampleComment")
	newsStatDailyColl = mo.NewCollection(db, "exampleNewsStatDaily")
	locationCool = mo.NewCollection(db, "exampleLocation")
}

type MigrateActions struct {
}

func (MigrateActions) Migrate_2021_11_23__09_52_CreateExmapleCommentJSONSchema(db *mo.Database) (err error) {
	f := mo.ExampleComment{}.Field()
	var jsonSchema = bson.M{
		"bsonType":             "object",
		"additionalProperties": false,
		"properties": bson.M{
			f.ID: bson.M{
				"bsonType": "objectId",
			},
			f.UserID: bson.M{
				"bsonType": "number",
			},
			f.NewsID: bson.M{
				"bsonType": "objectId",
			},
			f.Message: bson.M{
				"bsonType": "string",
			},
			f.Like: bson.M{
				"bsonType": "number",
			},
		},
	}
	var validator = bson.M{
		"$jsonSchema": jsonSchema,
	}
	opts := mongoOptions.CreateCollection().SetValidator(validator)
	err = db.Core.CreateCollection(context.TODO(), "exampleComment", opts)
	if err != nil {
		return
	}
	return
}
func (MigrateActions) Migrate_2021_11_23__09_52_CreateExampleNewsStatDailyIndexs(db *mo.Database) (err error) {

	f := mo.ExampleNewsStatDaily{}.Field()
	_, err = newsStatDailyColl.Core.Indexes().CreateOne(context.TODO(), mongo.IndexModel{
		Keys:    bson.D{{f.Date, 1}, {f.NewsID, 1}},
		Options: mongoOptions.Index().SetUnique(true),
	})
	if err != nil {
		return
	}
	return
}

// In a formal project you should use `go run cmd/migrate/main.go`, not running in init function
func ExampleMigrate() {
	mo.Migrate(db, &MigrateActions{})
}

func main() {
	/* In a formal environment ignore defer code */ var err error
	defer func() {
		if err != nil {
			xerr.PrintStack(err)
		}
	}()
	ctx := context.Background()
	exampleCommentList := mo.ManyExampleComment{
		{UserID: 1, Message: "a", NewsID: primitive.NewObjectID()},
		{UserID: 1, Message: "b", NewsID: primitive.NewObjectID()},
	}
	_, err = commentColl.InsertMany(ctx, &exampleCommentList, mo.InsertManyCommand{})
	if err != nil {
		return
	}
	log.Printf("ExampleCollection_InsertMany: %+v", exampleCommentList)
}
Output:

func (*Collection) InsertOne

func (c *Collection) InsertOne(ctx context.Context, document Document, cmd InsertOneCommand) (result ResultInsertOne, err error)
Example
package main

import (
	"context"

	xerr "github.com/goclub/error"

	mo "github.com/goclub/mongo"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"

	mongoOptions "go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
	"log"
)

var db *mo.Database
var commentColl *mo.Collection
var newsStatDailyColl *mo.Collection
var locationCool *mo.Collection

func init() {
	ExampleNewDatabase()
	ExampleNewCollection()
	ExampleMigrate()
}
func ExampleNewDatabase() {
	ctx := context.Background()
	client, err := mongo.Connect(ctx, mongoOptions.Client().ApplyURI(mo.ExampleReplicaSetURI))
	if err != nil {
		panic(err)
	}
	err = client.Ping(ctx, readpref.Primary())
	if err != nil {
		panic(err)
	}
	db = mo.NewDatabase(client, "goclub")
}
func ExampleNewCollection() {
	var err error
	defer func() {
		if err != nil {
			xerr.PrintStack(err)
		}
	}()
	commentColl = mo.NewCollection(db, "exampleComment")
	newsStatDailyColl = mo.NewCollection(db, "exampleNewsStatDaily")
	locationCool = mo.NewCollection(db, "exampleLocation")
}

type MigrateActions struct {
}

func (MigrateActions) Migrate_2021_11_23__09_52_CreateExmapleCommentJSONSchema(db *mo.Database) (err error) {
	f := mo.ExampleComment{}.Field()
	var jsonSchema = bson.M{
		"bsonType":             "object",
		"additionalProperties": false,
		"properties": bson.M{
			f.ID: bson.M{
				"bsonType": "objectId",
			},
			f.UserID: bson.M{
				"bsonType": "number",
			},
			f.NewsID: bson.M{
				"bsonType": "objectId",
			},
			f.Message: bson.M{
				"bsonType": "string",
			},
			f.Like: bson.M{
				"bsonType": "number",
			},
		},
	}
	var validator = bson.M{
		"$jsonSchema": jsonSchema,
	}
	opts := mongoOptions.CreateCollection().SetValidator(validator)
	err = db.Core.CreateCollection(context.TODO(), "exampleComment", opts)
	if err != nil {
		return
	}
	return
}
func (MigrateActions) Migrate_2021_11_23__09_52_CreateExampleNewsStatDailyIndexs(db *mo.Database) (err error) {

	f := mo.ExampleNewsStatDaily{}.Field()
	_, err = newsStatDailyColl.Core.Indexes().CreateOne(context.TODO(), mongo.IndexModel{
		Keys:    bson.D{{f.Date, 1}, {f.NewsID, 1}},
		Options: mongoOptions.Index().SetUnique(true),
	})
	if err != nil {
		return
	}
	return
}

// In a formal project you should use `go run cmd/migrate/main.go`, not running in init function
func ExampleMigrate() {
	mo.Migrate(db, &MigrateActions{})
}

func main() {
	ctx := context.Background()
	err := func() (err error) {
		exampleComment := mo.ExampleComment{
			UserID:  1,
			NewsID:  primitive.NewObjectID(),
			Message: "goclub/mongo",
		}
		_, err = commentColl.InsertOne(ctx, &exampleComment, mo.InsertOneCommand{})
		if err != nil {
			return
		}
		log.Printf("ExampleCollection_InsertOne: %+v", exampleComment)
		return
	}()
	if err != nil {
		log.Printf("%+v", err)
	}
}
Output:

func (*Collection) Paging

func (c *Collection) Paging(ctx context.Context, p Paging) (total uint64, err error)

func (*Collection) UpdateOne

func (c *Collection) UpdateOne(ctx context.Context, data FilterUpdate, cmd UpdateCommand) (updateResult *mongo.UpdateResult, err error)

type CountCommand

type CountCommand struct {
	// Specifies a collation to use for string comparisons during the operation. This option is only valid for MongoDB
	// versions >= 3.4. For previous server versions, the driver will return an error if this option is used. The
	// default value is nil, which means the default collation of the collection will be used.
	Collation *options.Collation

	// The index to use for the aggregation. This should either be the index name as a string or the index specification
	// as a document. The driver will return an error if the hint parameter is a multi-key map. The default value is nil,
	// which means that no hint will be sent.
	Hint interface{}

	// The maximum number of documents to count. The default value is 0, which means that there is no limit and all
	// documents matching the filter will be counted.
	Limit xtype.OptionUint64

	// The maximum amount of time that the query can run on the server. The default value is nil, meaning that there is
	// no time limit for query execution.
	MaxTime xtype.OptionDuration

	// The number of documents to skip before counting. The default value is 0.
	Skip xtype.OptionUint64
}

CountCommand represents options that can be used to configure a CountDocuments operation.

func (CountCommand) Options

func (c CountCommand) Options() (opt []*options.CountOptions)

type Database

type Database struct {
	Core *mongo.Database
	// contains filtered or unexported fields
}

func NewDatabase

func NewDatabase(client *mongo.Client, dbName string, opts ...*options.DatabaseOptions) *Database
Example
package main

import (
	"context"

	mo "github.com/goclub/mongo"
	"go.mongodb.org/mongo-driver/mongo"

	mongoOptions "go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
)

var db *mo.Database

func main() {
	ctx := context.Background()
	client, err := mongo.Connect(ctx, mongoOptions.Client().ApplyURI(mo.ExampleReplicaSetURI))
	if err != nil {
		panic(err)
	}
	err = client.Ping(ctx, readpref.Primary())
	if err != nil {
		panic(err)
	}
	db = mo.NewDatabase(client, "goclub")
}
Output:

type DefaultLifeCycle

type DefaultLifeCycle struct {
}

func (*DefaultLifeCycle) AfterInsert

func (v *DefaultLifeCycle) AfterInsert(data ResultInsertOne) error

func (*DefaultLifeCycle) AfterUpdate

func (v *DefaultLifeCycle) AfterUpdate() (err error)

func (*DefaultLifeCycle) BeforeInsert

func (v *DefaultLifeCycle) BeforeInsert() error

func (*DefaultLifeCycle) BeforeUpdate

func (v *DefaultLifeCycle) BeforeUpdate() (err error)

type DeleteCommand

type DeleteCommand struct {
	// Specifies a collation to use for string comparisons during the operation. This option is only valid for MongoDB
	// versions >= 3.4. For previous server versions, the driver will return an error if this option is used. The
	// default value is nil, which means the default collation of the collection will be used.
	Collation *options.Collation

	// The index to use for the operation. This should either be the index name as a string or the index specification
	// as a document. This option is only valid for MongoDB versions >= 4.4. Server versions >= 3.4 will return an error
	// if this option is specified. For server versions < 3.4, the driver will return a client-side error if this option
	// is specified. The driver will return an error if this option is specified during an unacknowledged write
	// operation. The driver will return an error if the hint parameter is a multi-key map. The default value is nil,
	// which means that no hint will be sent.
	Hint interface{}
}

DeleteCommand represents options that can be used to configure DeleteOne and DeleteMany operations.

func (DeleteCommand) Options

func (c DeleteCommand) Options() (opt []*options.DeleteOptions)

type Document

type Document interface {
	AfterInsert(data ResultInsertOne) (err error)
	BeforeInsert() (err error)
}

type ExampleComment

type ExampleComment struct {
	ID               primitive.ObjectID `bson:"_id,omitempty"`
	UserID           uint64             `bson:"userID"`
	NewsID           primitive.ObjectID `bson:"newsID"`
	Message          string             `bson:"message"`
	Like             uint64             `bson:"like"`
	DefaultLifeCycle `bson:"-"`
}

func (*ExampleComment) AfterInsert

func (v *ExampleComment) AfterInsert(result ResultInsertOne) (err error)

func (ExampleComment) Field

func (d ExampleComment) Field() (f struct {
	ID      string
	UserID  string
	NewsID  string
	Message string
	Like    string
})

type ExampleMovie

type ExampleMovie struct {
	ID               primitive.ObjectID `bson:"_id,omitempty"`
	Title            string             `bson:"title"`
	Year             int                `bson:"year"`
	Genres           []string           `bson:"genres"`
	Rated            string             `bson:"rated"`
	Languages        []string           `bson:"languages"`
	Released         time.Time          `bson:"released"`
	Awards           ExampleMovieAwards `bson:"awards"`
	Cast             []string           `bson:"cast"`
	Directors        []string           `bson:"directors"`
	LastUpdated      *time.Time         `bson:"lastupdated"`
	DefaultLifeCycle `bson:"-"`
}

func (*ExampleMovie) AfterInsert

func (v *ExampleMovie) AfterInsert(result ResultInsertOne) (err error)

type ExampleMovieAwards

type ExampleMovieAwards struct {
	Wins        int    `bson:"wins"`
	Nominations int    `bson:"nominations"`
	Text        string `bson:"text"`
}

type ExampleNewsStatDaily

type ExampleNewsStatDaily struct {
	ID         primitive.ObjectID `bson:"_id,omitempty"`
	Date       string             `bson:"date"`
	NewsID     primitive.ObjectID `bson:"newsID"`
	UV         uint64             `bson:"uv"`
	PV         uint64             `bson:"pv"`
	PlatformUV map[string]uint64  `bson:"platformUV"`
}

func (*ExampleNewsStatDaily) AfterInsert

func (v *ExampleNewsStatDaily) AfterInsert(result ResultInsertOne) (err error)

func (ExampleNewsStatDaily) Field

func (d ExampleNewsStatDaily) Field() (f struct {
	ID         string
	Date       string
	NewsID     string
	UV         string
	PV         string
	PlatformUV string
})

type FilterUpdate

type FilterUpdate struct {
	Filter interface{}
	Update interface{}
	Set    interface{}
	Inc    interface{}
}

type FindCommand

type FindCommand struct {
	LookupQuery  bool
	LookupResult bool
	// If true, the server can write temporary data to disk while executing the find operation. This option is only
	// valid for MongoDB versions >= 4.4. Server versions >= 3.2 will report an error if this option is specified. For
	// server versions < 3.2, the driver will return a client-side error if this option is specified. The default value
	// is false.
	AllowDiskUse xtype.OptionBool

	// If true, an operation on a sharded cluster can return partial results if some shards are down rather than
	// returning an error. The default value is false.
	AllowPartialResults xtype.OptionBool

	// The maximum number of documents to be included in each batch returned by the server.
	BatchSize xtype.OptionInt32

	// Specifies a collation to use for string comparisons during the operation. This option is only valid for MongoDB
	// versions >= 3.4. For previous server versions, the driver will return an error if this option is used. The
	// default value is nil, which means the default collation of the collection will be used.
	Collation *options.Collation

	// A string that will be included in server logs, profiling logs, and currentOp queries to help trace the operation.
	// The default is the empty string, which means that no comment will be included in the logs.
	Comment xtype.OptionString

	// Specifies the type of cursor that should be created for the operation. The default is NonTailable, which means
	// that the cursor will be closed by the server when the last batch of documents is retrieved.
	CursorType *options.CursorType

	// The index to use for the operation. This should either be the index name as a string or the index specification
	// as a document. The driver will return an error if the hint parameter is a multi-key map. The default value is nil,
	// which means that no hint will be sent.
	Hint interface{}

	// The maximum number of documents to return. The default value is 0, which means that all documents matching the
	// filter will be returned. A negative limit specifies that the resulting documents should be returned in a single
	// batch. The default value is 0.
	Limit xtype.OptionUint64

	// A document specifying the exclusive upper bound for a specific index. The default value is nil, which means that
	// there is no maximum value.
	Max interface{}

	// The maximum amount of time that the server should wait for new documents to satisfy a tailable cursor query.
	// This option is only valid for tailable await cursors (see the CursorType option for more information) and
	// MongoDB versions >= 3.2. For other cursor types or previous server versions, this option is ignored.
	MaxAwaitTime xtype.OptionDuration

	// The maximum amount of time that the query can run on the server. The default value is nil, meaning that there
	// is no time limit for query execution.
	MaxTime xtype.OptionDuration

	// A document specifying the inclusive lower bound for a specific index. The default value is 0, which means that
	// there is no minimum value.
	Min interface{}

	// If true, the cursor created by the operation will not timeout after a period of inactivity. The default value
	// is false.
	NoCursorTimeout xtype.OptionBool

	// This option is for internal replication use only and should not be set.
	//
	// Deprecated: This option has been deprecated in MongoDB version 4.4 and will be ignored by the server if it is
	// set.
	OplogReplay xtype.OptionBool

	// A document describing which fields will be included in the documents returned by the operation. The default value
	// is nil, which means all fields will be included.
	Projection interface{}

	// If true, the documents returned by the operation will only contain fields corresponding to the index used. The
	// default value is false.
	ReturnKey xtype.OptionBool

	// If true, a $recordId field with a record identifier will be included in the documents returned by the operation.
	// The default value is false.
	ShowRecordID xtype.OptionBool

	// The number of documents to skip before adding documents to the result. The default value is 0.
	Skip xtype.OptionUint64

	// If true, the cursor will not return a document more than once because of an intervening write operation. The
	// default value is false.
	//
	// Deprecated: This option has been deprecated in MongoDB version 3.6 and removed in MongoDB version 4.0.
	Snapshot xtype.OptionBool

	// A document specifying the order in which documents should be returned.  The driver will return an error if the
	// sort parameter is a multi-key map.
	Sort interface{}
}

func (FindCommand) Options

func (c FindCommand) Options() (opt []*options.FindOptions)

type FindOneCommand

type FindOneCommand struct {
	LookupQuery  bool
	LookupResult bool
	// If true, an operation on a sharded cluster can return partial results if some shards are down rather than
	// returning an error. The default value is false.
	AllowPartialResults xtype.OptionBool

	// Specifies a collation to use for string comparisons during the operation. This option is only valid for MongoDB
	// versions >= 3.4. For previous server versions, the driver will return an error if this option is used. The
	// default value is nil, which means the default collation of the collection will be used.
	Collation *options.Collation

	// A string that will be included in server logs, profiling logs, and currentOp queries to help trace the operation.
	// The default is the empty string, which means that no comment will be included in the logs.
	Comment xtype.OptionString

	// The index to use for the aggregation. This should either be the index name as a string or the index specification
	// as a document. The driver will return an error if the hint parameter is a multi-key map. The default value is nil,
	// which means that no hint will be sent.
	Hint interface{}

	// A document specifying the exclusive upper bound for a specific index. The default value is nil, which means that
	// there is no maximum value.
	Max interface{}

	// The maximum amount of time that the query can run on the server. The default value is nil, meaning that there
	// is no time limit for query execution.
	MaxTime xtype.OptionDuration

	// A document specifying the inclusive lower bound for a specific index. The default value is 0, which means that
	// there is no minimum value.
	Min interface{}

	// A document describing which fields will be included in the document returned by the operation. The default value
	// is nil, which means all fields will be included.
	Projection interface{}

	// If true, the document returned by the operation will only contain fields corresponding to the index used. The
	// default value is false.
	ReturnKey xtype.OptionBool

	// If true, a $recordId field with a record identifier will be included in the document returned by the operation.
	// The default value is false.
	ShowRecordID xtype.OptionBool

	// The number of documents to skip before selecting the document to be returned. The default value is 0.
	Sort interface{}

	// A document specifying the sort order to apply to the query. The first document in the sorted order will be
	// returned. The driver will return an error if the sort parameter is a multi-key map.
	Skip xtype.OptionUint64
}

func (FindOneCommand) Options

func (c FindOneCommand) Options() (opt []*options.FindOneOptions)

type InsertManyCommand

type InsertManyCommand struct {
	// If true, writes executed as part of the operation will opt out of document-level validation on the server. This
	// option is valid for MongoDB versions >= 3.2 and is ignored for previous server versions. The default value is
	// false. See https://docs.mongodb.com/manual/core/schema-validation/ for more information about document
	// validation.
	ByPassDocumentValidation xtype.OptionBool

	// If true, no writes will be executed after one fails. The default value is true.
	Ordered xtype.OptionBool
}

func (InsertManyCommand) Options

func (c InsertManyCommand) Options() (opt []*options.InsertManyOptions)

type InsertOneCommand

type InsertOneCommand struct {
	// If true, writes executed as part of the operation will opt out of document-level validation on the server. This
	// option is valid for MongoDB versions >= 3.2 and is ignored for previous server versions. The default value is
	// false. See https://docs.mongodb.com/manual/core/schema-validation/ for more information about document
	// validation.
	ByPassDocumentValidation xtype.OptionBool
}

func (InsertOneCommand) Options

func (c InsertOneCommand) Options() (opt []*options.InsertOneOptions)

type ManyDocument

type ManyDocument interface {
	ManyD() (documents []interface{}, err error)
	AfterInsertMany(result ResultInsertMany) (err error)
}

type ManyExampleComment

type ManyExampleComment []ExampleComment

func (ManyExampleComment) AfterInsertMany

func (many ManyExampleComment) AfterInsertMany(result ResultInsertMany) (err error)

func (ManyExampleComment) ManyD

func (many ManyExampleComment) ManyD() (documents []interface{}, err error)

type ManyExampleMovie

type ManyExampleMovie []ExampleMovie

func (ManyExampleMovie) AfterInsertMany

func (many ManyExampleMovie) AfterInsertMany(result ResultInsertMany) (err error)

func (ManyExampleMovie) ManyD

func (many ManyExampleMovie) ManyD() (documents []interface{}, err error)

type ManyExampleNewsStatDaily

type ManyExampleNewsStatDaily []ExampleNewsStatDaily

func (ManyExampleNewsStatDaily) AfterInsertMany

func (many ManyExampleNewsStatDaily) AfterInsertMany(result ResultInsertMany) (err error)

func (ManyExampleNewsStatDaily) ManyD

func (many ManyExampleNewsStatDaily) ManyD() (documents []interface{}, err error)

type Paging

type Paging struct {
	Filter   interface{}
	FindCmd  FindCommand
	SlicePtr interface{}
	CountCmd CountCommand
	Page     uint64
	PerPage  uint32
}
Example
package main

import (
	"context"

	xerr "github.com/goclub/error"

	mo "github.com/goclub/mongo"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"

	mongoOptions "go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
	"log"
)

var db *mo.Database
var commentColl *mo.Collection
var newsStatDailyColl *mo.Collection
var locationCool *mo.Collection

func init() {
	ExampleNewDatabase()
	ExampleNewCollection()
	ExampleMigrate()
}
func ExampleNewDatabase() {
	ctx := context.Background()
	client, err := mongo.Connect(ctx, mongoOptions.Client().ApplyURI(mo.ExampleReplicaSetURI))
	if err != nil {
		panic(err)
	}
	err = client.Ping(ctx, readpref.Primary())
	if err != nil {
		panic(err)
	}
	db = mo.NewDatabase(client, "goclub")
}
func ExampleNewCollection() {
	var err error
	defer func() {
		if err != nil {
			xerr.PrintStack(err)
		}
	}()
	commentColl = mo.NewCollection(db, "exampleComment")
	newsStatDailyColl = mo.NewCollection(db, "exampleNewsStatDaily")
	locationCool = mo.NewCollection(db, "exampleLocation")
}

type MigrateActions struct {
}

func (MigrateActions) Migrate_2021_11_23__09_52_CreateExmapleCommentJSONSchema(db *mo.Database) (err error) {
	f := mo.ExampleComment{}.Field()
	var jsonSchema = bson.M{
		"bsonType":             "object",
		"additionalProperties": false,
		"properties": bson.M{
			f.ID: bson.M{
				"bsonType": "objectId",
			},
			f.UserID: bson.M{
				"bsonType": "number",
			},
			f.NewsID: bson.M{
				"bsonType": "objectId",
			},
			f.Message: bson.M{
				"bsonType": "string",
			},
			f.Like: bson.M{
				"bsonType": "number",
			},
		},
	}
	var validator = bson.M{
		"$jsonSchema": jsonSchema,
	}
	opts := mongoOptions.CreateCollection().SetValidator(validator)
	err = db.Core.CreateCollection(context.TODO(), "exampleComment", opts)
	if err != nil {
		return
	}
	return
}
func (MigrateActions) Migrate_2021_11_23__09_52_CreateExampleNewsStatDailyIndexs(db *mo.Database) (err error) {

	f := mo.ExampleNewsStatDaily{}.Field()
	_, err = newsStatDailyColl.Core.Indexes().CreateOne(context.TODO(), mongo.IndexModel{
		Keys:    bson.D{{f.Date, 1}, {f.NewsID, 1}},
		Options: mongoOptions.Index().SetUnique(true),
	})
	if err != nil {
		return
	}
	return
}

// In a formal project you should use `go run cmd/migrate/main.go`, not running in init function
func ExampleMigrate() {
	mo.Migrate(db, &MigrateActions{})
}

func main() {
	/* In a formal environment ignore defer code */ var err error
	defer func() {
		if err != nil {
			xerr.PrintStack(err)
		}
	}()
	ctx := context.Background()
	field := mo.ExampleComment{}.Field()
	delResult, err := commentColl.DeleteMany(ctx, bson.M{
		field.Message: "paging",
	}, mo.DeleteCommand{})
	if err != nil {
		return
	}
	log.Print("delResult.DeletedCount:", delResult.DeletedCount)
	var insertList mo.ManyExampleComment
	for i := uint64(0); i < 111; i++ {
		insertList = append(insertList, mo.ExampleComment{
			UserID:  i + 1,
			NewsID:  primitive.NewObjectID(),
			Message: "paging",
			Like:    0,
		})
	}
	_, err = commentColl.InsertMany(ctx, &insertList, mo.InsertManyCommand{})
	if err != nil {
		return
	}
	var pagingList mo.ManyExampleComment
	total, err := commentColl.Paging(ctx, mo.Paging{
		Filter: bson.M{
			field.Message: "paging",
		},
		FindCmd:  mo.FindCommand{},
		SlicePtr: &pagingList,
		CountCmd: mo.CountCommand{},
		Page:     1,
		PerPage:  10,
	})
	if err != nil {
		return
	}
	log.Print("len(pagingList):", len(pagingList))
	log.Print("pagingList:", pagingList)
	log.Print("total:", total)
}
Output:

type ResultInsertMany

type ResultInsertMany struct {
	*mongo.InsertManyResult
}

func (ResultInsertMany) InsertedObjectIDs

func (res ResultInsertMany) InsertedObjectIDs() (insertedObjectIDs []primitive.ObjectID, err error)

type ResultInsertOne

type ResultInsertOne struct {
	*mongo.InsertOneResult
}

func (ResultInsertOne) InsertedObjectID

func (res ResultInsertOne) InsertedObjectID() (objectID primitive.ObjectID, err error)

type UpdateCommand

type UpdateCommand struct {
	// A set of filters specifying to which array elements an update should apply. This option is only valid for MongoDB
	// versions >= 3.6. For previous server versions, the driver will return an error if this option is used. The
	// default value is nil, which means the update will apply to all array elements.
	ArrayFilters *options.ArrayFilters

	// If true, writes executed as part of the operation will opt out of document-level validation on the server. This
	// option is valid for MongoDB versions >= 3.2 and is ignored for previous server versions. The default value is
	// false. See https://docs.mongodb.com/manual/core/schema-validation/ for more information about document
	// validation.
	BypassDocumentValidation xtype.OptionBool

	// Specifies a collation to use for string comparisons during the operation. This option is only valid for MongoDB
	// versions >= 3.4. For previous server versions, the driver will return an error if this option is used. The
	// default value is nil, which means the default collation of the collection will be used.
	Collation *options.Collation

	// The index to use for the operation. This should either be the index name as a string or the index specification
	// as a document. This option is only valid for MongoDB versions >= 4.2. Server versions >= 3.4 will return an error
	// if this option is specified. For server versions < 3.4, the driver will return a client-side error if this option
	// is specified. The driver will return an error if this option is specified during an unacknowledged write
	// operation. The driver will return an error if the hint parameter is a multi-key map. The default value is nil,
	// which means that no hint will be sent.
	Hint interface{}

	// If true, a new document will be inserted if the filter does not match any documents in the collection. The
	// default value is false.
	Upsert xtype.OptionBool
}

func (UpdateCommand) Options

func (c UpdateCommand) Options() (opt []*options.UpdateOptions)

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL