ChènMột MongoDB

Cách sử dụng cơ bản của trình điều khiển bắt đầu bằng việc tạo Máy khách từ chuỗi kết nối. Để làm như vậy, hãy gọi Kết nối

ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://foo:bar@localhost:27017"))
if err != nil { return err }

Thao tác này sẽ tạo một ứng dụng khách mới và bắt đầu theo dõi máy chủ MongoDB trên localhost. The Database and Collection types can be used to access the database

collection := client.Database("baz").Collection("qux")

A Collection can be used to query the database or insert documents

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID

Several methods return a cursor, which can be used like this

cur, err := collection.Find(context.Background(), bson.D{})
if err != nil { log.Fatal(err) }
defer cur.Close(context.Background())
for cur.Next(context.Background()) {
  // To decode into a struct, use cursor.Decode()
  result := struct{
    Foo string
    Bar int32
  }{}
  err := cur.Decode(&result)
  if err != nil { log.Fatal(err) }
  // do something with result...

  // To get the raw bson bytes use cursor.Current
  raw := cur.Current
  // do something with raw...
}
if err := cur.Err(); err != nil {
  return err
}

Cursor. All will decode all of the returned elements at once

var results []struct{
  Foo string
  Bar int32
}
if err = cur.All(context.Background(), &results); err != nil {
  log.Fatal(err)
}
// do something with results...

Methods that only return a single document will return a *SingleResult, which works like a *sql. Row

result := struct{
  Foo string
  Bar int32
}{}
filter := bson.D{{"hello", "world"}}
err := collection.FindOne(context.Background(), filter).Decode(&result)
if err != nil { return err }
// do something with result...

All Client, Collection, and Database methods that take parameters of type interface{} will return ErrNilDocument if nil is passed in for an interface{}

Additional examples can be found under the examples directory in the driver's repository and on the MongoDB website

Error Handling

Errors from the MongoDB server will implement the ServerError interface, which has functions to check for specific error codes, labels, and message substrings. These can be used to check for and handle specific errors. Some methods, like InsertMany and BulkWrite, can return an error representing multiple errors, and in those cases the ServerError functions will return true if any of the contained errors satisfy the check

There are also helper functions to check for certain specific types of errors

IsDuplicateKeyError(error)
IsNetworkError(error)
IsTimeout(error)

Potential DNS Issues

Building with Go 1. 11+ and using connection strings with the "mongodb+srv"[1] scheme is incompatible with some DNS servers in the wild due to the change introduced in https. //github. com/golang/go/issues/10622. If you receive an error with the message "cannot unmarshal DNS message" while running an operation, we suggest you use a different DNS server

Client Side Encryption

Client-side encryption is a new feature in MongoDB 4. 2 that allows specific data fields to be encrypted. Using this feature requires specifying the "cse" build tag during compilation

go build -tags cse

Note. Auto encryption is an enterprise- and Atlas-only feature

The libmongocrypt C library is required when using client-side encryption. Specific versions of libmongocrypt are required for different versions of the Go Driver

- Go Driver v1. 2. 0 requires libmongocrypt v1. 0. 0 or higher

- Go Driver v1. 5. 0 requires libmongocrypt v1. 1. 0 or higher

- Go Driver v1. 8. 0 requires libmongocrypt v1. 3. 0 or higher

- Go Driver v1. 10. 0 requires libmongocrypt v1. 5. 0 or higher. There is a severe bug when calling RewrapManyDataKey with libmongocrypt versions less than 1. 5. 2. This bug may result in data corruption. Please use libmongocrypt 1. 5. 2 or higher when calling RewrapManyDataKey

To install libmongocrypt, follow the instructions for your operating system

1. Linux. follow the instructions listed at to install the correct deb/rpm package

2. Mac. Follow the instructions listed at to install packages via brew and compile the libmongocrypt source code

3. Windows

mkdir -p c:/libmongocrypt/bin
mkdir -p c:/libmongocrypt/include

// Run the curl command in an empty directory as it will create new directories when unpacked.
curl https://s3.amazonaws.com/mciuploads/libmongocrypt/windows/latest_release/libmongocrypt.tar.gz --output libmongocrypt.tar.gz
tar -xvzf libmongocrypt.tar.gz

cp ./bin/mongocrypt.dll c:/libmongocrypt/bin
cp ./include/mongocrypt/*.h c:/libmongocrypt/include
export PATH=$PATH:/cygdrive/c/libmongocrypt/bin

libmongocrypt communicates with the mongocryptd process or mongo_crypt shared library for automatic encryption. See AutoEncryptionOpts. SetExtraOptions for options to configure use of mongocryptd or mongo_crypt

[1] See

Example (ClientSideEncryption)

// This would have to be the same master key that was used to create the
// encryption key.
localKey := make([]byte, 96)
if _, err := rand.Read(localKey); err != nil {
	log.Fatal(err)
}
kmsProviders := map[string]map[string]interface{}{
	"local": {
		"key": localKey,
	},
}
keyVaultNamespace := "encryption.__keyVault"

uri := "mongodb://localhost:27017"
autoEncryptionOpts := options.AutoEncryption().
	SetKeyVaultNamespace(keyVaultNamespace).
	SetKmsProviders(kmsProviders)
clientOpts := options.Client().
	ApplyURI(uri).
	SetAutoEncryptionOptions(autoEncryptionOpts)
client, err := Connect(context.TODO(), clientOpts)
if err != nil {
	log.Fatalf("Connect error: %v", err)
}
defer func() {
	if err = client.Disconnect(context.TODO()); err != nil {
		log.Fatalf("Disconnect error: %v", err)
	}
}()

collection := client.Database("test").Collection("coll")
if err := collection.Drop(context.TODO()); err != nil {
	log.Fatalf("Collection.Drop error: %v", err)
}

_, err = collection.InsertOne(
	context.TODO(),
	bson.D{{"encryptedField", "123456789"}})
if err != nil {
	log.Fatalf("InsertOne error: %v", err)
}
res, err := collection.FindOne(context.TODO(), bson.D{}).DecodeBytes()
if err != nil {
	log.Fatalf("FindOne error: %v", err)
}
fmt.Println(res)
collection := client.Database("baz").Collection("qux")
0

Example (ClientSideEncryptionCreateKey)

collection := client.Database("baz").Collection("qux")
1
collection := client.Database("baz").Collection("qux")
0

Example (ExplictEncryption)

collection := client.Database("baz").Collection("qux")
3
collection := client.Database("baz").Collection("qux")
0

Example (ExplictEncryptionWithAutomaticDecryption)

collection := client.Database("baz").Collection("qux")
5
collection := client.Database("baz").Collection("qux")
0

Index

  • deprecated
  • deprecated
    • deprecated
    • deprecated
    • deprecated
    • deprecated
    • deprecated
    • deprecated
    • deprecated
    • deprecated
    • deprecated
    • deprecated
    • deprecated
    • deprecated
    • deprecated
    • deprecated
    • deprecated
    • deprecated
    • deprecated
    • deprecated
    • deprecated
    • deprecated
    • deprecated
  • deprecated

Examples

Constants

This section is empty

Variables

collection := client.Database("baz").Collection("qux")
7

collection := client.Database("baz").Collection("qux")
8

ErrClientDisconnected is returned when disconnected Client is used to run an operation

collection := client.Database("baz").Collection("qux")
9

ErrEmptySlice được trả về khi một lát cắt trống được chuyển đến phương thức CRUD yêu cầu một lát cắt không trống

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
0

ErrInvalidIndexValue được trả về nếu một chỉ mục được tạo bằng tài liệu khóa có giá trị không phải là số hoặc chuỗi

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
1

ErrMultipleIndexDrop được trả về nếu nhiều chỉ mục sẽ bị loại bỏ khi gọi tới IndexView. DropOne

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
2

ErrNilDocument được trả về khi một tài liệu nil được chuyển đến một phương thức CRUD

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
3

ErrNilValue được trả về khi giá trị nil được truyền cho phương thức CRUD

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
4

ErrNoDocuments được trả về bởi các phương thức SingleResult khi thao tác tạo SingleResult không trả về bất kỳ tài liệu nào

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
5

ErrNonStringIndexName được trả về nếu chỉ mục được tạo với tên không phải là chuỗi

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
6

ErrUnacACKedWrite được trả về bởi các hoạt động có mối quan tâm ghi không được xác nhận

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
7

ErrWrongClient được trả về khi người dùng cố gắng vượt qua phiên được tạo bởi một ứng dụng khách khác với lệnh gọi phương thức đang sử dụng

Chức năng

func không dùng nữa được thêm vào v1. 1. 0

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
8

BatchCursorFromCursor returns a driver. BatchCursor for the given Cursor. If there is no underlying driver. BatchCursor, nil is returned

không dùng nữa. This is an unstable function because the driver. BatchCursor type exists in the "x" package. Neither this function nor the driver. BatchCursor type should be used by applications and may be changed or removed in any release

func added in v1. 5. 0

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
9

IsDuplicateKeyError returns true if err is a duplicate key error

func added in v1. 5. 0

cur, err := collection.Find(context.Background(), bson.D{})
if err != nil { log.Fatal(err) }
defer cur.Close(context.Background())
for cur.Next(context.Background()) {
  // To decode into a struct, use cursor.Decode()
  result := struct{
    Foo string
    Bar int32
  }{}
  err := cur.Decode(&result)
  if err != nil { log.Fatal(err) }
  // do something with result...

  // To get the raw bson bytes use cursor.Current
  raw := cur.Current
  // do something with raw...
}
if err := cur.Err(); err != nil {
  return err
}
0

IsNetworkError returns true if err is a network error

func added in v1. 5. 0

cur, err := collection.Find(context.Background(), bson.D{})
if err != nil { log.Fatal(err) }
defer cur.Close(context.Background())
for cur.Next(context.Background()) {
  // To decode into a struct, use cursor.Decode()
  result := struct{
    Foo string
    Bar int32
  }{}
  err := cur.Decode(&result)
  if err != nil { log.Fatal(err) }
  // do something with result...

  // To get the raw bson bytes use cursor.Current
  raw := cur.Current
  // do something with raw...
}
if err := cur.Err(); err != nil {
  return err
}
1

IsTimeout returns true if err is from a timeout

func added in v0. 0. 16

cur, err := collection.Find(context.Background(), bson.D{})
if err != nil { log.Fatal(err) }
defer cur.Close(context.Background())
for cur.Next(context.Background()) {
  // To decode into a struct, use cursor.Decode()
  result := struct{
    Foo string
    Bar int32
  }{}
  err := cur.Decode(&result)
  if err != nil { log.Fatal(err) }
  // do something with result...

  // To get the raw bson bytes use cursor.Current
  raw := cur.Current
  // do something with raw...
}
if err := cur.Err(); err != nil {
  return err
}
2

WithSession creates a new SessionContext from the ctx and sess parameters and uses it to call the fn callback. The SessionContext must be used as the Context parameter for any operations in the fn callback that should be executed under the session

WithSession is safe to call from multiple goroutines concurrently. However, the SessionContext passed to the WithSession callback function is not safe for concurrent use by multiple goroutines

Nếu tham số ctx đã chứa Phiên, thì Phiên đó sẽ được thay thế bằng phiên được cung cấp

Bất kỳ lỗi nào được trả về bởi lệnh gọi lại fn sẽ được trả về mà không có bất kỳ sửa đổi nào

Thí dụ

cur, err := collection.Find(context.Background(), bson.D{})
if err != nil { log.Fatal(err) }
defer cur.Close(context.Background())
for cur.Next(context.Background()) {
  // To decode into a struct, use cursor.Decode()
  result := struct{
    Foo string
    Bar int32
  }{}
  err := cur.Decode(&result)
  if err != nil { log.Fatal(err) }
  // do something with result...

  // To get the raw bson bytes use cursor.Current
  raw := cur.Current
  // do something with raw...
}
if err := cur.Err(); err != nil {
  return err
}
3_______1_______0

Chia sẻ Định dạng Chạy

các loại

loại được thêm vào v0. 0. 15

cur, err := collection.Find(context.Background(), bson.D{})
if err != nil { log.Fatal(err) }
defer cur.Close(context.Background())
for cur.Next(context.Background()) {
  // To decode into a struct, use cursor.Decode()
  result := struct{
    Foo string
    Bar int32
  }{}
  err := cur.Decode(&result)
  if err != nil { log.Fatal(err) }
  // do something with result...

  // To get the raw bson bytes use cursor.Current
  raw := cur.Current
  // do something with raw...
}
if err := cur.Err(); err != nil {
  return err
}
5

BSONAppender là một giao diện được triển khai bởi các loại có thể sắp xếp một loại được cung cấp thành các byte BSON và nối các byte đó vào []byte được cung cấp. AppendBSON có thể trả về lỗi non-nil error và non-nil []byte. Phương thức AppendBSON cũng có thể ghi BSON không đầy đủ vào []byte

loại được thêm vào v0. 0. 15

cur, err := collection.Find(context.Background(), bson.D{})
if err != nil { log.Fatal(err) }
defer cur.Close(context.Background())
for cur.Next(context.Background()) {
  // To decode into a struct, use cursor.Decode()
  result := struct{
    Foo string
    Bar int32
  }{}
  err := cur.Decode(&result)
  if err != nil { log.Fatal(err) }
  // do something with result...

  // To get the raw bson bytes use cursor.Current
  raw := cur.Current
  // do something with raw...
}
if err := cur.Err(); err != nil {
  return err
}
6

BSONAppenderFunc là một chức năng bộ điều hợp cho phép bất kỳ chức năng nào đáp ứng chữ ký phương thức AppendBSON được sử dụng khi sử dụng BSONAppender

func (BSONAppenderFunc) được thêm vào v0. 0. 15

cur, err := collection.Find(context.Background(), bson.D{})
if err != nil { log.Fatal(err) }
defer cur.Close(context.Background())
for cur.Next(context.Background()) {
  // To decode into a struct, use cursor.Decode()
  result := struct{
    Foo string
    Bar int32
  }{}
  err := cur.Decode(&result)
  if err != nil { log.Fatal(err) }
  // do something with result...

  // To get the raw bson bytes use cursor.Current
  raw := cur.Current
  // do something with raw...
}
if err := cur.Err(); err != nil {
  return err
}
7

AppendBSON triển khai giao diện BSONAppender

loại được thêm vào v0. 0. 4

cur, err := collection.Find(context.Background(), bson.D{})
if err != nil { log.Fatal(err) }
defer cur.Close(context.Background())
for cur.Next(context.Background()) {
  // To decode into a struct, use cursor.Decode()
  result := struct{
    Foo string
    Bar int32
  }{}
  err := cur.Decode(&result)
  if err != nil { log.Fatal(err) }
  // do something with result...

  // To get the raw bson bytes use cursor.Current
  raw := cur.Current
  // do something with raw...
}
if err := cur.Err(); err != nil {
  return err
}
8

BulkWriteError là lỗi xảy ra trong khi thực hiện một thao tác trong BulkWrite. Loại lỗi này chỉ được trả về như một phần của BulkWriteException

func (BulkWriteError) được thêm vào v0. 0. 4

cur, err := collection.Find(context.Background(), bson.D{})
if err != nil { log.Fatal(err) }
defer cur.Close(context.Background())
for cur.Next(context.Background()) {
  // To decode into a struct, use cursor.Decode()
  result := struct{
    Foo string
    Bar int32
  }{}
  err := cur.Decode(&result)
  if err != nil { log.Fatal(err) }
  // do something with result...

  // To get the raw bson bytes use cursor.Current
  raw := cur.Current
  // do something with raw...
}
if err := cur.Err(); err != nil {
  return err
}
9

Lỗi thực hiện giao diện lỗi

loại được thêm vào v0. 0. 16

var results []struct{
  Foo string
  Bar int32
}
if err = cur.All(context.Background(), &results); err != nil {
  log.Fatal(err)
}
// do something with results...
0

BulkWriteException là loại lỗi được trả về bởi thao tác BulkWrite và InsertMany

func (BulkWriteException) được thêm vào v0. 0. 16

var results []struct{
  Foo string
  Bar int32
}
if err = cur.All(context.Background(), &results); err != nil {
  log.Fatal(err)
}
// do something with results...
1

Lỗi thực hiện giao diện lỗi

func (BulkWriteException) được thêm vào v1. 5. 0

var results []struct{
  Foo string
  Bar int32
}
if err = cur.All(context.Background(), &results); err != nil {
  log.Fatal(err)
}
// do something with results...
2

HasErrorCode trả về true nếu bất kỳ lỗi nào có mã được chỉ định

func (BulkWriteException) được thêm vào v1. 5. 0

var results []struct{
  Foo string
  Bar int32
}
if err = cur.All(context.Background(), &results); err != nil {
  log.Fatal(err)
}
// do something with results...
3

HasErrorCodeWithMessage trả về true nếu bất kỳ lỗi nào chứa mã và thông báo được chỉ định

func (BulkWriteException) added in v1. 4. 0

var results []struct{
  Foo string
  Bar int32
}
if err = cur.All(context.Background(), &results); err != nil {
  log.Fatal(err)
}
// do something with results...
4

HasErrorLabel trả về true nếu lỗi chứa nhãn đã chỉ định

func (BulkWriteException) được thêm vào v1. 5. 0

var results []struct{
  Foo string
  Bar int32
}
if err = cur.All(context.Background(), &results); err != nil {
  log.Fatal(err)
}
// do something with results...
5

HasErrorMessage trả về true nếu lỗi chứa thông báo đã chỉ định

loại được thêm vào v0. 0. 16

var results []struct{
  Foo string
  Bar int32
}
if err = cur.All(context.Background(), &results); err != nil {
  log.Fatal(err)
}
// do something with results...
6

BulkWriteResult là loại kết quả được trả về bởi thao tác BulkWrite

loại được thêm vào v0. 3. 0

var results []struct{
  Foo string
  Bar int32
}
if err = cur.All(context.Background(), &results); err != nil {
  log.Fatal(err)
}
// do something with results...
7

ChangeStream được sử dụng để lặp lại một luồng sự kiện. Mỗi sự kiện có thể được giải mã thành loại Go thông qua phương thức Giải mã hoặc được truy cập dưới dạng BSON thô thông qua trường Hiện tại. Loại này không an toàn cho goroutine và không được sử dụng đồng thời bởi nhiều goroutine. Để biết thêm thông tin về các luồng thay đổi, hãy xem https. //www. mongodb. com/docs/manual/changeStreams/

func (*ChangeStream) được thêm vào v0. 3. 0

var results []struct{
  Foo string
  Bar int32
}
if err = cur.All(context.Background(), &results); err != nil {
  log.Fatal(err)
}
// do something with results...
8

Đóng đóng luồng thay đổi này và con trỏ bên dưới. Next và TryNext không được gọi sau khi Close đã được gọi. Đóng là idempotent. Sau cuộc gọi đầu tiên, mọi cuộc gọi tiếp theo sẽ không thay đổi trạng thái

func (*ChangeStream) được thêm vào v0. 3. 0

var results []struct{
  Foo string
  Bar int32
}
if err = cur.All(context.Background(), &results); err != nil {
  log.Fatal(err)
}
// do something with results...
9

Giải mã sẽ sắp xếp lại tài liệu sự kiện hiện tại thành val và trả về bất kỳ lỗi nào từ quy trình sắp xếp lại mà không có bất kỳ sửa đổi nào. Nếu val là nil hoặc là nil được nhập, một lỗi sẽ được trả về

func (*ChangeStream) được thêm vào v0. 3. 0

result := struct{
  Foo string
  Bar int32
}{}
filter := bson.D{{"hello", "world"}}
err := collection.FindOne(context.Background(), filter).Decode(&result)
if err != nil { return err }
// do something with result...
0

Err trả về lỗi cuối cùng mà luồng thay đổi nhìn thấy hoặc không nếu không có lỗi nào xảy ra

func (*ChangeStream) được thêm vào v0. 3. 0

result := struct{
  Foo string
  Bar int32
}{}
filter := bson.D{{"hello", "world"}}
err := collection.FindOne(context.Background(), filter).Decode(&result)
if err != nil { return err }
// do something with result...
1

ID trả về ID cho luồng thay đổi này hoặc 0 nếu con trỏ đã bị đóng hoặc hết

func (*ChangeStream) được thêm vào v0. 3. 0

result := struct{
  Foo string
  Bar int32
}{}
filter := bson.D{{"hello", "world"}}
err := collection.FindOne(context.Background(), filter).Decode(&result)
if err != nil { return err }
// do something with result...
2

Tiếp theo nhận sự kiện tiếp theo cho luồng thay đổi này. Nó trả về true nếu không có lỗi và tài liệu sự kiện tiếp theo có sẵn

Các khối tiếp theo cho đến khi có sự kiện, xảy ra lỗi hoặc ctx hết hạn. Nếu ctx hết hạn, lỗi sẽ được đặt thành ctx. Lỗi (). Trong trường hợp lỗi, Next sẽ trả về false

Nếu Next trả về false, các cuộc gọi tiếp theo cũng sẽ trả về false

Thí dụ

result := struct{
  Foo string
  Bar int32
}{}
filter := bson.D{{"hello", "world"}}
err := collection.FindOne(context.Background(), filter).Decode(&result)
if err != nil { return err }
// do something with result...
3
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

func (*ChangeStream) được thêm vào v1. 1. 0

result := struct{
  Foo string
  Bar int32
}{}
filter := bson.D{{"hello", "world"}}
err := collection.FindOne(context.Background(), filter).Decode(&result)
if err != nil { return err }
// do something with result...
5

ResumeToken trả về mã thông báo tiếp tục được lưu trong bộ nhớ cache cuối cùng cho luồng thay đổi này hoặc không nếu mã thông báo tiếp tục chưa được lưu trữ

Thí dụ

result := struct{
  Foo string
  Bar int32
}{}
filter := bson.D{{"hello", "world"}}
err := collection.FindOne(context.Background(), filter).Decode(&result)
if err != nil { return err }
// do something with result...
6_______1_______0

Chia sẻ Định dạng Chạy

func (*ChangeStream) được thêm vào v1. 2. 0

result := struct{
  Foo string
  Bar int32
}{}
filter := bson.D{{"hello", "world"}}
err := collection.FindOne(context.Background(), filter).Decode(&result)
if err != nil { return err }
// do something with result...
8

TryNext cố gắng nhận sự kiện tiếp theo cho luồng thay đổi này. Nó trả về true nếu không có lỗi và tài liệu sự kiện tiếp theo có sẵn

TryNext trả về false nếu luồng thay đổi bị đóng bởi máy chủ, xảy ra lỗi khi nhận các thay đổi từ máy chủ, thay đổi tiếp theo chưa có sẵn hoặc ctx hết hạn. Nếu ctx hết hạn, lỗi sẽ được đặt thành ctx. Lỗi ()

Nếu TryNext trả về false và đã xảy ra lỗi hoặc luồng thay đổi đã bị đóng (i. e. cs. Lỗi (). = không. cs. ID() == 0), các lần thử tiếp theo cũng sẽ trả về false. Otherwise, it is safe to call TryNext again until a change is available

Phương pháp này yêu cầu phiên bản trình điều khiển >= 1. 2. 0

Thí dụ

result := struct{
  Foo string
  Bar int32
}{}
filter := bson.D{{"hello", "world"}}
err := collection.FindOne(context.Background(), filter).Decode(&result)
if err != nil { return err }
// do something with result...
9
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

loại

IsDuplicateKeyError(error)
IsNetworkError(error)
IsTimeout(error)
1

Máy khách là một tay cầm đại diện cho một nhóm các kết nối tới triển khai MongoDB. Nó an toàn để sử dụng đồng thời bởi nhiều goroutine

The Client type opens and closes connections automatically and maintains a pool of idle connections. Để biết các tùy chọn cấu hình nhóm kết nối, hãy xem tài liệu về loại ClientOptions trong gói mongo/options

Thí dụ

IsDuplicateKeyError(error)
IsNetworkError(error)
IsTimeout(error)
2
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

func được thêm vào v0. 0. 3

IsDuplicateKeyError(error)
IsNetworkError(error)
IsTimeout(error)
4

Connect tạo một Client mới và sau đó khởi tạo nó bằng phương thức Connect. Điều này tương đương với việc gọi NewClient theo sau là Client. Connect

When creating an options. ClientOptions, thứ tự các phương thức được gọi là vấn đề. Later Set* methods will overwrite the values from previous Set* method invocations. Điều này bao gồm phương thức ApplyURI. Điều này cho phép người gọi xác định thứ tự ưu tiên cho ứng dụng tùy chọn. Chẳng hạn, nếu ApplyURI được gọi trước SetAuth, Thông tin xác thực từ SetAuth sẽ ghi đè lên các giá trị từ chuỗi kết nối. Nếu ApplyURI được gọi sau SetAuth, thì các giá trị của nó sẽ ghi đè lên các giá trị từ SetAuth

Tham số opts được xử lý bằng các tùy chọn. MergeClientOptions, sẽ ghi đè lên toàn bộ các trường tùy chọn của các tùy chọn trước đó, không ghi đè một phần. Ví dụ: nếu Tên người dùng được đặt trong trường Xác thực cho tùy chọn đầu tiên và Mật khẩu được đặt cho tùy chọn thứ hai nhưng không có Tên người dùng, thì sau khi hợp nhất, trường Tên người dùng sẽ trống

The NewClient function does not do any I/O and returns an error if the given options are invalid. The Client. Connect method starts background goroutines to monitor the state of the deployment and does not do any I/O in the main goroutine to prevent the main goroutine from blocking. Therefore, it will not error if the deployment is down

The Client. Ping method can be used to verify that the deployment is successfully connected and the Client was correctly configured

Example (AWS)

IsDuplicateKeyError(error)
IsNetworkError(error)
IsTimeout(error)
5
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

Example (Direct)

IsDuplicateKeyError(error)
IsNetworkError(error)
IsTimeout(error)
7
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

Example (Kerberos)

IsDuplicateKeyError(error)
IsNetworkError(error)
IsTimeout(error)
9
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

Example (PLAIN)

go build -tags cse
1
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

Example (Ping)

go build -tags cse
3
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

Example (ReplicaSet)

go build -tags cse
5
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

Example (SCRAM)

go build -tags cse
7
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

Example (SRV)

go build -tags cse
9
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

Example (Sharded)

mkdir -p c:/libmongocrypt/bin
mkdir -p c:/libmongocrypt/include

// Run the curl command in an empty directory as it will create new directories when unpacked.
curl https://s3.amazonaws.com/mciuploads/libmongocrypt/windows/latest_release/libmongocrypt.tar.gz --output libmongocrypt.tar.gz
tar -xvzf libmongocrypt.tar.gz

cp ./bin/mongocrypt.dll c:/libmongocrypt/bin
cp ./include/mongocrypt/*.h c:/libmongocrypt/include
export PATH=$PATH:/cygdrive/c/libmongocrypt/bin
1
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

Example (StableAPI)

mkdir -p c:/libmongocrypt/bin
mkdir -p c:/libmongocrypt/include

// Run the curl command in an empty directory as it will create new directories when unpacked.
curl https://s3.amazonaws.com/mciuploads/libmongocrypt/windows/latest_release/libmongocrypt.tar.gz --output libmongocrypt.tar.gz
tar -xvzf libmongocrypt.tar.gz

cp ./bin/mongocrypt.dll c:/libmongocrypt/bin
cp ./include/mongocrypt/*.h c:/libmongocrypt/include
export PATH=$PATH:/cygdrive/c/libmongocrypt/bin
3
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

Example (X509)

mkdir -p c:/libmongocrypt/bin
mkdir -p c:/libmongocrypt/include

// Run the curl command in an empty directory as it will create new directories when unpacked.
curl https://s3.amazonaws.com/mciuploads/libmongocrypt/windows/latest_release/libmongocrypt.tar.gz --output libmongocrypt.tar.gz
tar -xvzf libmongocrypt.tar.gz

cp ./bin/mongocrypt.dll c:/libmongocrypt/bin
cp ./include/mongocrypt/*.h c:/libmongocrypt/include
export PATH=$PATH:/cygdrive/c/libmongocrypt/bin
5
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

func

mkdir -p c:/libmongocrypt/bin
mkdir -p c:/libmongocrypt/include

// Run the curl command in an empty directory as it will create new directories when unpacked.
curl https://s3.amazonaws.com/mciuploads/libmongocrypt/windows/latest_release/libmongocrypt.tar.gz --output libmongocrypt.tar.gz
tar -xvzf libmongocrypt.tar.gz

cp ./bin/mongocrypt.dll c:/libmongocrypt/bin
cp ./include/mongocrypt/*.h c:/libmongocrypt/include
export PATH=$PATH:/cygdrive/c/libmongocrypt/bin
7

NewClient creates a new client to connect to a deployment specified by the uri

When creating an options. ClientOptions, thứ tự các phương thức được gọi là vấn đề. Later Set* methods will overwrite the values from previous Set* method invocations. Điều này bao gồm phương thức ApplyURI. Điều này cho phép người gọi xác định thứ tự ưu tiên cho ứng dụng tùy chọn. Chẳng hạn, nếu ApplyURI được gọi trước SetAuth, Thông tin xác thực từ SetAuth sẽ ghi đè lên các giá trị từ chuỗi kết nối. Nếu ApplyURI được gọi sau SetAuth, thì các giá trị của nó sẽ ghi đè lên các giá trị từ SetAuth

Tham số opts được xử lý bằng các tùy chọn. MergeClientOptions, sẽ ghi đè lên toàn bộ các trường tùy chọn của các tùy chọn trước đó, không ghi đè một phần. Ví dụ: nếu Tên người dùng được đặt trong trường Xác thực cho tùy chọn đầu tiên và Mật khẩu được đặt cho tùy chọn thứ hai nhưng không có Tên người dùng, thì sau khi hợp nhất, trường Tên người dùng sẽ trống

func (*Client) added in v0. 0. 3

mkdir -p c:/libmongocrypt/bin
mkdir -p c:/libmongocrypt/include

// Run the curl command in an empty directory as it will create new directories when unpacked.
curl https://s3.amazonaws.com/mciuploads/libmongocrypt/windows/latest_release/libmongocrypt.tar.gz --output libmongocrypt.tar.gz
tar -xvzf libmongocrypt.tar.gz

cp ./bin/mongocrypt.dll c:/libmongocrypt/bin
cp ./include/mongocrypt/*.h c:/libmongocrypt/include
export PATH=$PATH:/cygdrive/c/libmongocrypt/bin
8

Connect initializes the Client by starting background monitoring goroutines. If the Client was created using the NewClient function, this method must be called before a Client can be used

Connect starts background goroutines to monitor the state of the deployment and does not do any I/O in the main goroutine. The Client. Ping method can be used to verify that the connection was created successfully

func (*Client)

mkdir -p c:/libmongocrypt/bin
mkdir -p c:/libmongocrypt/include

// Run the curl command in an empty directory as it will create new directories when unpacked.
curl https://s3.amazonaws.com/mciuploads/libmongocrypt/windows/latest_release/libmongocrypt.tar.gz --output libmongocrypt.tar.gz
tar -xvzf libmongocrypt.tar.gz

cp ./bin/mongocrypt.dll c:/libmongocrypt/bin
cp ./include/mongocrypt/*.h c:/libmongocrypt/include
export PATH=$PATH:/cygdrive/c/libmongocrypt/bin
9

Database returns a handle for a database with the given name configured with the given DatabaseOptions

func (*Client) added in v0. 0. 3

// This would have to be the same master key that was used to create the
// encryption key.
localKey := make([]byte, 96)
if _, err := rand.Read(localKey); err != nil {
	log.Fatal(err)
}
kmsProviders := map[string]map[string]interface{}{
	"local": {
		"key": localKey,
	},
}
keyVaultNamespace := "encryption.__keyVault"

uri := "mongodb://localhost:27017"
autoEncryptionOpts := options.AutoEncryption().
	SetKeyVaultNamespace(keyVaultNamespace).
	SetKmsProviders(kmsProviders)
clientOpts := options.Client().
	ApplyURI(uri).
	SetAutoEncryptionOptions(autoEncryptionOpts)
client, err := Connect(context.TODO(), clientOpts)
if err != nil {
	log.Fatalf("Connect error: %v", err)
}
defer func() {
	if err = client.Disconnect(context.TODO()); err != nil {
		log.Fatalf("Disconnect error: %v", err)
	}
}()

collection := client.Database("test").Collection("coll")
if err := collection.Drop(context.TODO()); err != nil {
	log.Fatalf("Collection.Drop error: %v", err)
}

_, err = collection.InsertOne(
	context.TODO(),
	bson.D{{"encryptedField", "123456789"}})
if err != nil {
	log.Fatalf("InsertOne error: %v", err)
}
res, err := collection.FindOne(context.TODO(), bson.D{}).DecodeBytes()
if err != nil {
	log.Fatalf("FindOne error: %v", err)
}
fmt.Println(res)
0

Disconnect closes sockets to the topology referenced by this Client. It will shut down any monitoring goroutines, close the idle connection pool, and will wait until all the in use connections have been returned to the connection pool and closed before returning. If the context expires via cancellation, deadline, or timeout before the in use connections have returned, the in use connections will be closed, resulting in the failure of any in flight read or write operations. If this method returns with no errors, all connections associated with this Client have been closed

func (*Client) added in v0. 0. 3

// This would have to be the same master key that was used to create the
// encryption key.
localKey := make([]byte, 96)
if _, err := rand.Read(localKey); err != nil {
	log.Fatal(err)
}
kmsProviders := map[string]map[string]interface{}{
	"local": {
		"key": localKey,
	},
}
keyVaultNamespace := "encryption.__keyVault"

uri := "mongodb://localhost:27017"
autoEncryptionOpts := options.AutoEncryption().
	SetKeyVaultNamespace(keyVaultNamespace).
	SetKmsProviders(kmsProviders)
clientOpts := options.Client().
	ApplyURI(uri).
	SetAutoEncryptionOptions(autoEncryptionOpts)
client, err := Connect(context.TODO(), clientOpts)
if err != nil {
	log.Fatalf("Connect error: %v", err)
}
defer func() {
	if err = client.Disconnect(context.TODO()); err != nil {
		log.Fatalf("Disconnect error: %v", err)
	}
}()

collection := client.Database("test").Collection("coll")
if err := collection.Drop(context.TODO()); err != nil {
	log.Fatalf("Collection.Drop error: %v", err)
}

_, err = collection.InsertOne(
	context.TODO(),
	bson.D{{"encryptedField", "123456789"}})
if err != nil {
	log.Fatalf("InsertOne error: %v", err)
}
res, err := collection.FindOne(context.TODO(), bson.D{}).DecodeBytes()
if err != nil {
	log.Fatalf("FindOne error: %v", err)
}
fmt.Println(res)
1

ListDatabaseNames executes a listDatabases command and returns a slice containing the names of all of the databases on the server

The filter parameter must be a document containing query operators and can be used to select which databases are included in the result. It cannot be nil. An empty document (e. g. bson. D{}) should be used to include all databases

The opts parameter can be used to specify options for this operation (see the options. ListDatabasesOptions documentation. )

For more information about the command, see https. //www. mongodb. com/docs/manual/reference/command/listDatabases/

Thí dụ

// This would have to be the same master key that was used to create the
// encryption key.
localKey := make([]byte, 96)
if _, err := rand.Read(localKey); err != nil {
	log.Fatal(err)
}
kmsProviders := map[string]map[string]interface{}{
	"local": {
		"key": localKey,
	},
}
keyVaultNamespace := "encryption.__keyVault"

uri := "mongodb://localhost:27017"
autoEncryptionOpts := options.AutoEncryption().
	SetKeyVaultNamespace(keyVaultNamespace).
	SetKmsProviders(kmsProviders)
clientOpts := options.Client().
	ApplyURI(uri).
	SetAutoEncryptionOptions(autoEncryptionOpts)
client, err := Connect(context.TODO(), clientOpts)
if err != nil {
	log.Fatalf("Connect error: %v", err)
}
defer func() {
	if err = client.Disconnect(context.TODO()); err != nil {
		log.Fatalf("Disconnect error: %v", err)
	}
}()

collection := client.Database("test").Collection("coll")
if err := collection.Drop(context.TODO()); err != nil {
	log.Fatalf("Collection.Drop error: %v", err)
}

_, err = collection.InsertOne(
	context.TODO(),
	bson.D{{"encryptedField", "123456789"}})
if err != nil {
	log.Fatalf("InsertOne error: %v", err)
}
res, err := collection.FindOne(context.TODO(), bson.D{}).DecodeBytes()
if err != nil {
	log.Fatalf("FindOne error: %v", err)
}
fmt.Println(res)
2
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

func (*Client) added in v0. 0. 3

// This would have to be the same master key that was used to create the
// encryption key.
localKey := make([]byte, 96)
if _, err := rand.Read(localKey); err != nil {
	log.Fatal(err)
}
kmsProviders := map[string]map[string]interface{}{
	"local": {
		"key": localKey,
	},
}
keyVaultNamespace := "encryption.__keyVault"

uri := "mongodb://localhost:27017"
autoEncryptionOpts := options.AutoEncryption().
	SetKeyVaultNamespace(keyVaultNamespace).
	SetKmsProviders(kmsProviders)
clientOpts := options.Client().
	ApplyURI(uri).
	SetAutoEncryptionOptions(autoEncryptionOpts)
client, err := Connect(context.TODO(), clientOpts)
if err != nil {
	log.Fatalf("Connect error: %v", err)
}
defer func() {
	if err = client.Disconnect(context.TODO()); err != nil {
		log.Fatalf("Disconnect error: %v", err)
	}
}()

collection := client.Database("test").Collection("coll")
if err := collection.Drop(context.TODO()); err != nil {
	log.Fatalf("Collection.Drop error: %v", err)
}

_, err = collection.InsertOne(
	context.TODO(),
	bson.D{{"encryptedField", "123456789"}})
if err != nil {
	log.Fatalf("InsertOne error: %v", err)
}
res, err := collection.FindOne(context.TODO(), bson.D{}).DecodeBytes()
if err != nil {
	log.Fatalf("FindOne error: %v", err)
}
fmt.Println(res)
4

ListDatabases thực thi lệnh listDatabases và trả về kết quả

The filter parameter must be a document containing query operators and can be used to select which databases are included in the result. It cannot be nil. An empty document (e. g. bson. D{}) should be used to include all databases

Tham số opts có thể được sử dụng để chỉ định các tùy chọn cho thao tác này (xem các tùy chọn. ListDatabasesOptions tài liệu)

For more information about the command, see https. //www. mongodb. com/docs/manual/reference/command/listDatabases/

func (*Máy khách) được thêm vào v1. 2. 0

// This would have to be the same master key that was used to create the
// encryption key.
localKey := make([]byte, 96)
if _, err := rand.Read(localKey); err != nil {
	log.Fatal(err)
}
kmsProviders := map[string]map[string]interface{}{
	"local": {
		"key": localKey,
	},
}
keyVaultNamespace := "encryption.__keyVault"

uri := "mongodb://localhost:27017"
autoEncryptionOpts := options.AutoEncryption().
	SetKeyVaultNamespace(keyVaultNamespace).
	SetKmsProviders(kmsProviders)
clientOpts := options.Client().
	ApplyURI(uri).
	SetAutoEncryptionOptions(autoEncryptionOpts)
client, err := Connect(context.TODO(), clientOpts)
if err != nil {
	log.Fatalf("Connect error: %v", err)
}
defer func() {
	if err = client.Disconnect(context.TODO()); err != nil {
		log.Fatalf("Disconnect error: %v", err)
	}
}()

collection := client.Database("test").Collection("coll")
if err := collection.Drop(context.TODO()); err != nil {
	log.Fatalf("Collection.Drop error: %v", err)
}

_, err = collection.InsertOne(
	context.TODO(),
	bson.D{{"encryptedField", "123456789"}})
if err != nil {
	log.Fatalf("InsertOne error: %v", err)
}
res, err := collection.FindOne(context.TODO(), bson.D{}).DecodeBytes()
if err != nil {
	log.Fatalf("FindOne error: %v", err)
}
fmt.Println(res)
5

NumberSessionsInProgress trả về số phiên đã được bắt đầu cho khách hàng này nhưng chưa bị đóng (i. e. EndSession chưa được gọi)

func (*Máy khách) được thêm vào v0. 0. 14

// This would have to be the same master key that was used to create the
// encryption key.
localKey := make([]byte, 96)
if _, err := rand.Read(localKey); err != nil {
	log.Fatal(err)
}
kmsProviders := map[string]map[string]interface{}{
	"local": {
		"key": localKey,
	},
}
keyVaultNamespace := "encryption.__keyVault"

uri := "mongodb://localhost:27017"
autoEncryptionOpts := options.AutoEncryption().
	SetKeyVaultNamespace(keyVaultNamespace).
	SetKmsProviders(kmsProviders)
clientOpts := options.Client().
	ApplyURI(uri).
	SetAutoEncryptionOptions(autoEncryptionOpts)
client, err := Connect(context.TODO(), clientOpts)
if err != nil {
	log.Fatalf("Connect error: %v", err)
}
defer func() {
	if err = client.Disconnect(context.TODO()); err != nil {
		log.Fatalf("Disconnect error: %v", err)
	}
}()

collection := client.Database("test").Collection("coll")
if err := collection.Drop(context.TODO()); err != nil {
	log.Fatalf("Collection.Drop error: %v", err)
}

_, err = collection.InsertOne(
	context.TODO(),
	bson.D{{"encryptedField", "123456789"}})
if err != nil {
	log.Fatalf("InsertOne error: %v", err)
}
res, err := collection.FindOne(context.TODO(), bson.D{}).DecodeBytes()
if err != nil {
	log.Fatalf("FindOne error: %v", err)
}
fmt.Println(res)
6

Ping gửi lệnh ping để xác minh rằng máy khách có thể kết nối với triển khai

Tham số rp được sử dụng để xác định máy chủ nào được chọn cho hoạt động. Nếu nó là không, tùy chọn đọc của khách hàng được sử dụng

Nếu máy chủ ngừng hoạt động, Ping sẽ cố gắng chọn máy chủ cho đến khi hết thời gian chờ chọn máy chủ của khách hàng. Điều này có thể được cấu hình thông qua ClientOptions. Tùy chọn SetServerSelectionTimeout khi tạo Máy khách mới. Sau khi hết thời gian chờ, lỗi lựa chọn máy chủ được trả về

Việc sử dụng Ping làm giảm khả năng phục hồi của ứng dụng vì các ứng dụng khởi động sẽ gặp lỗi nếu máy chủ tạm thời không khả dụng hoặc bị lỗi (e. g. trong quá trình tự động tính tỷ lệ do tải tăng đột biến)

func (*Máy khách) được thêm vào v0. 0. 10

// This would have to be the same master key that was used to create the
// encryption key.
localKey := make([]byte, 96)
if _, err := rand.Read(localKey); err != nil {
	log.Fatal(err)
}
kmsProviders := map[string]map[string]interface{}{
	"local": {
		"key": localKey,
	},
}
keyVaultNamespace := "encryption.__keyVault"

uri := "mongodb://localhost:27017"
autoEncryptionOpts := options.AutoEncryption().
	SetKeyVaultNamespace(keyVaultNamespace).
	SetKmsProviders(kmsProviders)
clientOpts := options.Client().
	ApplyURI(uri).
	SetAutoEncryptionOptions(autoEncryptionOpts)
client, err := Connect(context.TODO(), clientOpts)
if err != nil {
	log.Fatalf("Connect error: %v", err)
}
defer func() {
	if err = client.Disconnect(context.TODO()); err != nil {
		log.Fatalf("Disconnect error: %v", err)
	}
}()

collection := client.Database("test").Collection("coll")
if err := collection.Drop(context.TODO()); err != nil {
	log.Fatalf("Collection.Drop error: %v", err)
}

_, err = collection.InsertOne(
	context.TODO(),
	bson.D{{"encryptedField", "123456789"}})
if err != nil {
	log.Fatalf("InsertOne error: %v", err)
}
res, err := collection.FindOne(context.TODO(), bson.D{}).DecodeBytes()
if err != nil {
	log.Fatalf("FindOne error: %v", err)
}
fmt.Println(res)
7

StartSession bắt đầu một phiên mới được định cấu hình với các tùy chọn đã cho

StartSession không thực sự giao tiếp với máy chủ và sẽ không báo lỗi nếu máy khách bị ngắt kết nối

StartSession an toàn để gọi đồng thời từ nhiều goroutine. Tuy nhiên, Phiên được trả về bởi StartSession không an toàn để sử dụng đồng thời bởi nhiều goroutine

Nếu các tùy chọn DefaultReadConcern, DefaultWriteConcern hoặc DefaultReadPreference không được đặt, mối quan tâm đọc, mối quan tâm ghi hoặc tùy chọn đọc của máy khách sẽ được sử dụng tương ứng

Ví dụ (WithTransaction)

// This would have to be the same master key that was used to create the
// encryption key.
localKey := make([]byte, 96)
if _, err := rand.Read(localKey); err != nil {
	log.Fatal(err)
}
kmsProviders := map[string]map[string]interface{}{
	"local": {
		"key": localKey,
	},
}
keyVaultNamespace := "encryption.__keyVault"

uri := "mongodb://localhost:27017"
autoEncryptionOpts := options.AutoEncryption().
	SetKeyVaultNamespace(keyVaultNamespace).
	SetKmsProviders(kmsProviders)
clientOpts := options.Client().
	ApplyURI(uri).
	SetAutoEncryptionOptions(autoEncryptionOpts)
client, err := Connect(context.TODO(), clientOpts)
if err != nil {
	log.Fatalf("Connect error: %v", err)
}
defer func() {
	if err = client.Disconnect(context.TODO()); err != nil {
		log.Fatalf("Disconnect error: %v", err)
	}
}()

collection := client.Database("test").Collection("coll")
if err := collection.Drop(context.TODO()); err != nil {
	log.Fatalf("Collection.Drop error: %v", err)
}

_, err = collection.InsertOne(
	context.TODO(),
	bson.D{{"encryptedField", "123456789"}})
if err != nil {
	log.Fatalf("InsertOne error: %v", err)
}
res, err := collection.FindOne(context.TODO(), bson.D{}).DecodeBytes()
if err != nil {
	log.Fatalf("FindOne error: %v", err)
}
fmt.Println(res)
8
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

func (*Máy khách) được thêm vào v1. 11. 0

collection := client.Database("baz").Collection("qux")
00

Thời gian chờ trả về thời gian chờ đã đặt cho khách hàng này

func (*Máy khách) được thêm vào v0. 0. 16

collection := client.Database("baz").Collection("qux")
01

UseSession tạo một Session mới và sử dụng nó để tạo một SessionContext mới, được sử dụng để gọi hàm gọi lại fn. Tham số SessionContext phải được sử dụng làm tham số Ngữ cảnh cho bất kỳ hoạt động nào trong cuộc gọi lại fn sẽ được thực thi trong một phiên. Sau khi lệnh gọi lại trả về, Phiên đã tạo sẽ kết thúc, nghĩa là mọi giao dịch đang thực hiện do fn bắt đầu sẽ bị hủy bỏ ngay cả khi fn trả về lỗi

UseSession an toàn khi gọi đồng thời từ nhiều goroutine. Tuy nhiên, SessionContext được chuyển đến hàm gọi lại UseSession không an toàn để nhiều goroutine sử dụng đồng thời

Nếu tham số ctx đã chứa Phiên, thì Phiên đó sẽ được thay thế bằng phiên mới được tạo

Bất kỳ lỗi nào được trả về bởi lệnh gọi lại fn sẽ được trả về mà không có bất kỳ sửa đổi nào

func (*Máy khách) được thêm vào v0. 0. 16

collection := client.Database("baz").Collection("qux")
02

UseSessionWithOptions hoạt động giống như UseSession nhưng sử dụng SessionOptions đã cho để tạo Phiên

UseSessionWithOptions an toàn khi gọi đồng thời từ nhiều goroutine. Tuy nhiên, SessionContext được chuyển đến hàm gọi lại UseSessionWithOptions không an toàn để nhiều goroutine sử dụng đồng thời

Thí dụ

collection := client.Database("baz").Collection("qux")
03____1_______0

Chia sẻ Định dạng Chạy

func (*Máy khách) được thêm vào v0. 1. 0

collection := client.Database("baz").Collection("qux")
05

Watch trả về một luồng thay đổi cho tất cả các thay đổi khi triển khai. Xem https. //www. mongodb. com/docs/manual/changeStreams/ để biết thêm thông tin về các luồng thay đổi

Máy khách phải được định cấu hình với đa số mối quan tâm đã đọc hoặc không có mối quan tâm đã đọc nào để luồng thay đổi được tạo thành công

Tham số đường ống phải là một mảng tài liệu, mỗi tệp đại diện cho một giai đoạn đường ống. Đường ống không được rỗng hoặc trống. Tất cả các tài liệu giai đoạn phải khác không. Xem https. //www. mongodb. com/docs/manual/changeStreams/ để biết danh sách các giai đoạn quy trình có thể được sử dụng với các luồng thay đổi. Đối với một đường ống của bson. tài liệu D, mongo. Loại {} đường ống có thể được sử dụng

Tham số opts có thể được sử dụng để chỉ định các tùy chọn để tạo luồng thay đổi (xem các tùy chọn. ChangeStreamOptions tài liệu)

Thí dụ

collection := client.Database("baz").Collection("qux")
06
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

loại được thêm vào v1. 2. 0

collection := client.Database("baz").Collection("qux")
08

ClientEncryption được sử dụng để tạo khóa dữ liệu và mã hóa và giải mã rõ ràng các giá trị BSON

func được thêm vào v1. 2. 0

collection := client.Database("baz").Collection("qux")
09

NewClientEncryption tạo một phiên bản ClientEncryption mới được định cấu hình với các tùy chọn đã cho

func (*ClientEncryption) được thêm vào v1. 10. 0

collection := client.Database("baz").Collection("qux")
10

AddKeyAltName thêm keyAltName vào mảng keyAltNames của tài liệu khóa trong bộ sưu tập kho khóa với UUID đã cho (kiểu con nhị phân BSON 0x04). Trả về phiên bản trước của tài liệu chính

func (*ClientEncryption) được thêm vào v1. 2. 0

collection := client.Database("baz").Collection("qux")
11

Đóng dọn sạch mọi tài nguyên được liên kết với phiên bản ClientEncryption. Điều này bao gồm việc ngắt kết nối phiên bản Key-vault Client

func (*ClientEncryption) được thêm vào v1. 2. 0

collection := client.Database("baz").Collection("qux")
12

CreateDataKey creates a new key document and inserts into the key vault collection. Trả về _id của tài liệu đã tạo dưới dạng UUID (kiểu con nhị phân BSON 0x04)

func (*ClientEncryption) được thêm vào v1. 2. 0

collection := client.Database("baz").Collection("qux")
13

Giải mã giải mã một giá trị được mã hóa (nhị phân BSON của loại phụ 6) và trả về giá trị BSON ban đầu

func (*ClientEncryption) được thêm vào v1. 10. 0

collection := client.Database("baz").Collection("qux")
14

DeleteKey xóa tài liệu khóa có UUID đã cho (loại con nhị phân BSON 0x04) khỏi bộ sưu tập kho khóa. Trả về kết quả của thao tác deleteOne() nội bộ trên bộ sưu tập kho tiền chính

func (*ClientEncryption) được thêm vào v1. 2. 0

collection := client.Database("baz").Collection("qux")
15

Mã hóa mã hóa giá trị BSON bằng khóa và thuật toán đã cho. Trả về một giá trị được mã hóa (nhị phân BSON của loại phụ 6)

func (*ClientEncryption) được thêm vào v1. 10. 0

collection := client.Database("baz").Collection("qux")
16

GetKey tìm thấy một tài liệu khóa duy nhất với UUID đã cho (kiểu con nhị phân BSON 0x04). Trả về kết quả của thao tác find() nội bộ trên bộ sưu tập key vault

func (*ClientEncryption) được thêm vào v1. 10. 0

collection := client.Database("baz").Collection("qux")
17

GetKeyByAltName trả về một tài liệu quan trọng trong bộ sưu tập kho lưu trữ khóa với keyAltName đã cho

func (*ClientEncryption) được thêm vào v1. 10. 0

collection := client.Database("baz").Collection("qux")
18

GetKeys tìm thấy tất cả các tài liệu trong bộ sưu tập kho khóa. Trả về kết quả của thao tác find() nội bộ trên bộ sưu tập key vault

func (*ClientEncryption) được thêm vào v1. 10. 0

collection := client.Database("baz").Collection("qux")
19

RemoveKeyAltName xóa keyAltName khỏi mảng keyAltNames của tài liệu khóa trong bộ sưu tập kho khóa với UUID đã cho (kiểu con nhị phân BSON 0x04). Trả về phiên bản trước của tài liệu chính

func (*ClientEncryption) được thêm vào v1. 10. 0

collection := client.Database("baz").Collection("qux")
20

RewrapManyDataKey giải mã và mã hóa tất cả các khóa dữ liệu phù hợp bằng một giá trị masterKey mới có thể. Đối với tất cả các tài liệu phù hợp, phương thức này sẽ ghi đè lên "masterKey", "updateDate" và "keyMaterial". Do lỗi, một số khóa dữ liệu phù hợp có thể đã được gói lại. libmongocrypt 1. 5. 2 là bắt buộc. Lỗi được trả về nếu phiên bản libmongocrypt được phát hiện nhỏ hơn 1. 5. 2

loại

collection := client.Database("baz").Collection("qux")
21

Bộ sưu tập là một điều khiển cho bộ sưu tập MongoDB. Nó an toàn để sử dụng đồng thời bởi nhiều goroutine

chức năng (*Bộ sưu tập)

collection := client.Database("baz").Collection("qux")
22

Tổng hợp thực thi một lệnh tổng hợp đối với bộ sưu tập và trả về một con trỏ trên các tài liệu kết quả

Tham số đường ống phải là một mảng tài liệu, mỗi tài liệu đại diện cho một giai đoạn tổng hợp. Đường ống không thể là không nhưng có thể trống. Tất cả các tài liệu giai đoạn phải khác không. Đối với một đường ống của bson. tài liệu D, mongo. Loại đường ống có thể được sử dụng. Xem danh sách các giai đoạn hợp lệ trong tập hợp

Tham số opts có thể được sử dụng để chỉ định các tùy chọn cho hoạt động (xem các tùy chọn. Tài liệu về tùy chọn tổng hợp. )

Để biết thêm thông tin về lệnh, xem https. //www. mongodb. com/docs/manual/reference/command/aggregate/

Thí dụ

collection := client.Database("baz").Collection("qux")
23
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

func (*Collection) added in v0. 0. 16

collection := client.Database("baz").Collection("qux")
25

BulkWrite performs a bulk write operation (https. //www. mongodb. com/docs/manual/core/bulk-write-operations/)

The models parameter must be a slice of operations to be executed in this bulk write. It cannot be nil or empty. All of the models must be non-nil. See the mongo. WriteModel documentation for a list of valid model types and examples of how they should be used

The opts parameter can be used to specify options for the operation (see the options. BulkWriteOptions documentation. )

Thí dụ

collection := client.Database("baz").Collection("qux")
26
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

func (*Collection) added in v0. 0. 9

collection := client.Database("baz").Collection("qux")
28

Clone creates a copy of the Collection configured with the given CollectionOptions. The specified options are merged with the existing options on the collection, with the specified options taking precedence

func (*Collection) added in v0. 0. 11

collection := client.Database("baz").Collection("qux")
29

CountDocuments returns the number of documents in the collection. For a fast count of the documents in the collection, see the EstimatedDocumentCount method

The filter parameter must be a document and can be used to select which documents contribute to the count. It cannot be nil. An empty document (e. g. bson. D{}) should be used to count all documents in the collection. This will result in a full collection scan

The opts parameter can be used to specify options for the operation (see the options. CountOptions documentation)

Thí dụ

collection := client.Database("baz").Collection("qux")
30
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

func (*Collection) added in v0. 0. 15

collection := client.Database("baz").Collection("qux")
32

Database returns the Database that was used to create the Collection

chức năng (*Bộ sưu tập)

collection := client.Database("baz").Collection("qux")
33

DeleteMany thực thi lệnh xóa để xóa tài liệu khỏi bộ sưu tập

The filter parameter must be a document containing query operators and can be used to select the documents to be deleted. It cannot be nil. An empty document (e. g. con trai. D{}) nên được sử dụng để xóa tất cả các tài liệu trong bộ sưu tập. Nếu bộ lọc không khớp với bất kỳ tài liệu nào, thao tác sẽ thành công và DeleteResult với DeletedCount bằng 0 sẽ được trả về

Tham số opts có thể được sử dụng để chỉ định các tùy chọn cho hoạt động (xem các tùy chọn. DeleteOptions tài liệu)

Để biết thêm thông tin về lệnh, xem https. //www. mongodb. com/docs/manual/tham khảo/lệnh/xóa/

Thí dụ

collection := client.Database("baz").Collection("qux")
34
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

chức năng (*Bộ sưu tập)

collection := client.Database("baz").Collection("qux")
36

DeleteOne thực thi lệnh xóa để xóa tối đa một tài liệu khỏi bộ sưu tập

Tham số bộ lọc phải là một tài liệu chứa các toán tử truy vấn và có thể được sử dụng để chọn tài liệu sẽ bị xóa. Nó không thể là con số không. Nếu bộ lọc không khớp với bất kỳ tài liệu nào, thao tác sẽ thành công và DeleteResult với DeletedCount bằng 0 sẽ được trả về. Nếu bộ lọc phù hợp với nhiều tài liệu, một tài liệu sẽ được chọn từ bộ phù hợp

Tham số opts có thể được sử dụng để chỉ định các tùy chọn cho hoạt động (xem các tùy chọn. DeleteOptions tài liệu)

Để biết thêm thông tin về lệnh, xem https. //www. mongodb. com/docs/manual/tham khảo/lệnh/xóa/

Thí dụ

collection := client.Database("baz").Collection("qux")
37______1_______0

Chia sẻ Định dạng Chạy

chức năng (*Bộ sưu tập)

collection := client.Database("baz").Collection("qux")
39

Distinct thực thi một lệnh riêng biệt để tìm các giá trị duy nhất cho một trường được chỉ định trong bộ sưu tập

Tham số fieldName chỉ định tên trường cho các giá trị riêng biệt sẽ được trả về

Tham số bộ lọc phải là một tài liệu chứa toán tử truy vấn và có thể được sử dụng để chọn tài liệu nào được xem xét. Nó không thể là con số không. An empty document (e. g. con trai. D{}) nên được sử dụng để chọn tất cả các tài liệu

Tham số opts có thể được sử dụng để chỉ định các tùy chọn cho hoạt động (xem các tùy chọn. tài liệu DistinctOptions)

Để biết thêm thông tin về lệnh, xem https. //www. mongodb. com/docs/manual/reference/command/distinct/

Thí dụ

collection := client.Database("baz").Collection("qux")
40_______1_______0

Chia sẻ Định dạng Chạy

func (*Bộ sưu tập) được thêm vào v0. 0. 4

collection := client.Database("baz").Collection("qux")
42

Thả rơi bộ sưu tập trên máy chủ. Phương pháp này bỏ qua các lỗi "không tìm thấy không gian tên" để có thể loại bỏ một bộ sưu tập không tồn tại trên máy chủ một cách an toàn

func (*Collection) added in v0. 0. 11

collection := client.Database("baz").Collection("qux")
43

EstimateDocumentCount thực thi lệnh đếm và trả về ước tính số lượng tài liệu trong bộ sưu tập bằng cách sử dụng siêu dữ liệu của bộ sưu tập

Tham số opts có thể được sử dụng để chỉ định các tùy chọn cho hoạt động (xem các tùy chọn. tài liệu của EstimateDocumentCountOptions)

Để biết thêm thông tin về lệnh, xem https. //www. mongodb. com/docs/manual/reference/command/count/

Thí dụ

collection := client.Database("baz").Collection("qux")
44
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

chức năng (*Bộ sưu tập)

collection := client.Database("baz").Collection("qux")
46

Tìm thực thi lệnh tìm và trả về Con trỏ trên các tài liệu phù hợp trong bộ sưu tập

Tham số bộ lọc phải là tài liệu chứa toán tử truy vấn và có thể được sử dụng để chọn tài liệu nào được đưa vào kết quả. Nó không thể là con số không. Một tài liệu trống (e. g. con trai. D{}) nên được sử dụng để bao gồm tất cả các tài liệu

Tham số opts có thể được sử dụng để chỉ định các tùy chọn cho hoạt động (xem các tùy chọn. tài liệu FindOptions)

Để biết thêm thông tin về lệnh, xem https. //www. mongodb. com/docs/manual/reference/command/find/

Thí dụ

collection := client.Database("baz").Collection("qux")
47____1_______0

Chia sẻ Định dạng Chạy

chức năng (*Bộ sưu tập)

collection := client.Database("baz").Collection("qux")
49

FindOne thực thi lệnh tìm và trả về SingleResult cho một tài liệu trong bộ sưu tập

Tham số bộ lọc phải là một tài liệu chứa toán tử truy vấn và có thể được sử dụng để chọn tài liệu được trả về. Nó không thể là con số không. Nếu bộ lọc không khớp với bất kỳ tài liệu nào, một SingleResult có lỗi được đặt thành ErrNoDocuments sẽ được trả về. Nếu bộ lọc phù hợp với nhiều tài liệu, một tài liệu sẽ được chọn từ bộ phù hợp

Tham số opts có thể được sử dụng để chỉ định các tùy chọn cho thao tác này (xem các tùy chọn. Tài liệu FindOneOptions)

Để biết thêm thông tin về lệnh, xem https. //www. mongodb. com/docs/manual/reference/command/find/

Thí dụ

collection := client.Database("baz").Collection("qux")
50
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

chức năng (*Bộ sưu tập)

collection := client.Database("baz").Collection("qux")
52

FindOneAndDelete thực thi lệnh findAndModify để xóa tối đa một tài liệu trong bộ sưu tập. và trả lại tài liệu như nó xuất hiện trước khi xóa

Tham số bộ lọc phải là một tài liệu chứa các toán tử truy vấn và có thể được sử dụng để chọn tài liệu sẽ bị xóa. Nó không thể là con số không. Nếu bộ lọc không khớp với bất kỳ tài liệu nào, SingleResult có lỗi được đặt thành ErrNoDocuments sẽ được trả về. Nếu bộ lọc phù hợp với nhiều tài liệu, một tài liệu sẽ được chọn từ bộ phù hợp

Tham số opts có thể được sử dụng để chỉ định các tùy chọn cho hoạt động (xem các tùy chọn. Tài liệu FindOneAndDeleteOptions)

Để biết thêm thông tin về lệnh, xem https. //www. mongodb. com/docs/manual/reference/command/findAndModify/

Thí dụ

collection := client.Database("baz").Collection("qux")
53
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

chức năng (*Bộ sưu tập)

collection := client.Database("baz").Collection("qux")
55

FindOneAndReplace thực thi lệnh findAndModify để thay thế tối đa một tài liệu trong bộ sưu tập và trả về tài liệu như nó xuất hiện trước khi thay thế

Tham số bộ lọc phải là một tài liệu chứa các toán tử truy vấn và có thể được sử dụng để chọn tài liệu được thay thế. Nó không thể là con số không. Nếu bộ lọc không khớp với bất kỳ tài liệu nào, SingleResult có lỗi được đặt thành ErrNoDocuments sẽ được trả về. Nếu bộ lọc phù hợp với nhiều tài liệu, một tài liệu sẽ được chọn từ bộ phù hợp

Tham số thay thế phải là tài liệu sẽ được sử dụng để thay thế tài liệu đã chọn. Nó không thể là không và không thể chứa bất kỳ toán tử cập nhật nào (https. //www. mongodb. com/docs/manual/reference/operator/update/)

Tham số opts có thể được sử dụng để chỉ định các tùy chọn cho hoạt động (xem các tùy chọn. Tài liệu FindOneAndReplaceOptions)

Để biết thêm thông tin về lệnh, xem https. //www. mongodb. com/docs/manual/reference/command/findAndModify/

Thí dụ

collection := client.Database("baz").Collection("qux")
56
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

chức năng (*Bộ sưu tập)

collection := client.Database("baz").Collection("qux")
58

FindOneAndUpdate thực thi lệnh findAndModify để cập nhật tối đa một tài liệu trong bộ sưu tập và trả về tài liệu như nó xuất hiện trước khi cập nhật

Tham số bộ lọc phải là một tài liệu chứa các toán tử truy vấn và có thể được sử dụng để chọn tài liệu sẽ được cập nhật. Nó không thể là con số không. Nếu bộ lọc không khớp với bất kỳ tài liệu nào, SingleResult có lỗi được đặt thành ErrNoDocuments sẽ được trả về. Nếu bộ lọc phù hợp với nhiều tài liệu, một tài liệu sẽ được chọn từ bộ phù hợp

Tham số cập nhật phải là một tài liệu chứa toán tử cập nhật (https. //www. mongodb. com/docs/manual/reference/operator/update/) và có thể được sử dụng để chỉ định các sửa đổi sẽ được thực hiện đối với tài liệu đã chọn. Nó không thể là không hoặc trống

Tham số opts có thể được sử dụng để chỉ định các tùy chọn cho hoạt động (xem các tùy chọn. tài liệu FindOneAndUpdateOptions)

Để biết thêm thông tin về lệnh, xem https. //www. mongodb. com/docs/manual/reference/command/findAndModify/

Thí dụ

collection := client.Database("baz").Collection("qux")
59
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

func (*Bộ sưu tập) được thêm vào v0. 0. 3

collection := client.Database("baz").Collection("qux")
61

Các chỉ mục trả về một phiên bản IndexView có thể được sử dụng để thực hiện các thao tác trên các chỉ mục cho bộ sưu tập

chức năng (*Bộ sưu tập)

collection := client.Database("baz").Collection("qux")
62

InsertMany thực thi lệnh chèn để chèn nhiều tài liệu vào bộ sưu tập. Nếu ghi lỗi xảy ra trong quá trình hoạt động (e. g. lỗi khóa trùng lặp), phương thức này trả về lỗi BulkWriteException

Tham số tài liệu phải là một lát tài liệu để chèn. Slice không được rỗng hoặc rỗng. Tất cả các phần tử phải khác không. Đối với bất kỳ tài liệu nào không có trường _id khi được chuyển đổi thành BSON, một tài liệu sẽ được tự động thêm vào tài liệu được sắp xếp theo thứ tự. Tài liệu gốc sẽ không được sửa đổi. Các giá trị _id cho tài liệu đã chèn có thể được truy xuất từ ​​trường InsertedIDs của InsertManyResult được trả về

Tham số opts có thể được sử dụng để chỉ định các tùy chọn cho hoạt động (xem các tùy chọn. Tài liệu InsertManyOptions. )

Để biết thêm thông tin về lệnh, xem https. //www. mongodb. com/docs/manual/tham khảo/lệnh/chèn/

Thí dụ

collection := client.Database("baz").Collection("qux")
63
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

chức năng (*Bộ sưu tập)

collection := client.Database("baz").Collection("qux")
65

InsertOne thực thi lệnh chèn để chèn một tài liệu vào bộ sưu tập

Tham số tài liệu phải là tài liệu được chèn. Nó không thể là con số không. Nếu tài liệu không có trường _id khi được chuyển đổi thành BSON, một trường sẽ được tự động thêm vào tài liệu được sắp xếp theo thứ tự. Tài liệu gốc sẽ không được sửa đổi. The _id can be retrieved from the InsertedID field of the returned InsertOneResult

Tham số opts có thể được sử dụng để chỉ định các tùy chọn cho hoạt động (xem các tùy chọn. Tài liệu InsertOneOptions. )

Để biết thêm thông tin về lệnh, xem https. //www. mongodb. com/docs/manual/tham khảo/lệnh/chèn/

Thí dụ

collection := client.Database("baz").Collection("qux")
66
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

func (*Bộ sưu tập) được thêm vào v0. 0. 4

collection := client.Database("baz").Collection("qux")
68

Tên trả về tên của bộ sưu tập

chức năng (*Bộ sưu tập)

collection := client.Database("baz").Collection("qux")
69

ReplaceOne thực thi lệnh cập nhật để thay thế tối đa một tài liệu trong bộ sưu tập

Tham số bộ lọc phải là một tài liệu chứa các toán tử truy vấn và có thể được sử dụng để chọn tài liệu được thay thế. Nó không thể là con số không. Nếu bộ lọc không khớp với bất kỳ tài liệu nào, thao tác sẽ thành công và UpdateResult với MatchedCount bằng 0 sẽ được trả về. Nếu bộ lọc phù hợp với nhiều tài liệu, một tài liệu sẽ được chọn từ bộ phù hợp và MatchedCount sẽ bằng 1

Tham số thay thế phải là tài liệu sẽ được sử dụng để thay thế tài liệu đã chọn. Nó không thể là không và không thể chứa bất kỳ toán tử cập nhật nào (https. //www. mongodb. com/docs/manual/reference/operator/update/)

Tham số opts có thể được sử dụng để chỉ định các tùy chọn cho hoạt động (xem các tùy chọn. tài liệu ReplaceOptions)

Để biết thêm thông tin về lệnh, xem https. //www. mongodb. com/docs/manual/tham khảo/lệnh/cập nhật/

Thí dụ

collection := client.Database("baz").Collection("qux")
70
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

func (*Bộ sưu tập) được thêm vào v1. 5. 0

collection := client.Database("baz").Collection("qux")
72

UpdateByID thực thi lệnh cập nhật để cập nhật tài liệu có giá trị _id khớp với ID được cung cấp trong bộ sưu tập. Điều này tương đương với việc chạy UpdateOne(ctx, bson. D{{"_id", id}}, cập nhật, chọn. )

Tham số id là _id của tài liệu sẽ được cập nhật. Nó không thể là con số không. Nếu ID không khớp với bất kỳ tài liệu nào, thao tác sẽ thành công và UpdateResult với MatchedCount bằng 0 sẽ được trả về

Tham số cập nhật phải là một tài liệu chứa toán tử cập nhật (https. //www. mongodb. com/docs/manual/reference/operator/update/) và có thể được sử dụng để chỉ định các sửa đổi sẽ được thực hiện đối với tài liệu đã chọn. Nó không thể là không hoặc trống

Tham số opts có thể được sử dụng để chỉ định các tùy chọn cho hoạt động (xem các tùy chọn. UpdateOptions tài liệu)

Để biết thêm thông tin về lệnh, xem https. //www. mongodb. com/docs/manual/tham khảo/lệnh/cập nhật/

chức năng (*Bộ sưu tập)

collection := client.Database("baz").Collection("qux")
73

UpdateMany thực thi lệnh cập nhật để cập nhật tài liệu trong bộ sưu tập

Tham số bộ lọc phải là một tài liệu chứa các toán tử truy vấn và có thể được sử dụng để chọn các tài liệu sẽ được cập nhật. Nó không thể là con số không. Nếu bộ lọc không khớp với bất kỳ tài liệu nào, thao tác sẽ thành công và UpdateResult với MatchedCount bằng 0 sẽ được trả về

Tham số cập nhật phải là một tài liệu chứa toán tử cập nhật (https. //www. mongodb. com/docs/manual/reference/operator/update/) và có thể được sử dụng để chỉ định các sửa đổi sẽ được thực hiện đối với các tài liệu đã chọn. Nó không thể là không hoặc trống

Tham số opts có thể được sử dụng để chỉ định các tùy chọn cho hoạt động (xem các tùy chọn. UpdateOptions tài liệu)

Để biết thêm thông tin về lệnh, xem https. //www. mongodb. com/docs/manual/tham khảo/lệnh/cập nhật/

Thí dụ

collection := client.Database("baz").Collection("qux")
74____1_______0

Chia sẻ Định dạng Chạy

chức năng (*Bộ sưu tập)

collection := client.Database("baz").Collection("qux")
76

UpdateOne thực thi lệnh cập nhật để cập nhật nhiều nhất một tài liệu trong bộ sưu tập

Tham số bộ lọc phải là một tài liệu chứa các toán tử truy vấn và có thể được sử dụng để chọn tài liệu sẽ được cập nhật. Nó không thể là con số không. Nếu bộ lọc không khớp với bất kỳ tài liệu nào, thao tác sẽ thành công và UpdateResult với MatchedCount bằng 0 sẽ được trả về. Nếu bộ lọc phù hợp với nhiều tài liệu, một tài liệu sẽ được chọn từ bộ phù hợp và MatchedCount sẽ bằng 1

Tham số cập nhật phải là một tài liệu chứa toán tử cập nhật (https. //www. mongodb. com/docs/manual/reference/operator/update/) và có thể được sử dụng để chỉ định các sửa đổi sẽ được thực hiện đối với tài liệu đã chọn. Nó không thể là không hoặc trống

Tham số opts có thể được sử dụng để chỉ định các tùy chọn cho hoạt động (xem các tùy chọn. UpdateOptions tài liệu)

Để biết thêm thông tin về lệnh, xem https. //www. mongodb. com/docs/manual/tham khảo/lệnh/cập nhật/

Thí dụ

collection := client.Database("baz").Collection("qux")
77
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

func (*Bộ sưu tập) được thêm vào v0. 0. 2

collection := client.Database("baz").Collection("qux")
79

Đồng hồ trả về một luồng thay đổi cho tất cả các thay đổi trên bộ sưu tập tương ứng. Xem https. //www. mongodb. com/docs/manual/changeStreams/ để biết thêm thông tin về các luồng thay đổi

Bộ sưu tập phải được định cấu hình với đa số mối quan tâm đã đọc hoặc không có mối quan tâm đã đọc nào để luồng thay đổi được tạo thành công

Tham số đường ống phải là một mảng tài liệu, mỗi tệp đại diện cho một giai đoạn đường ống. Đường ống không thể là không nhưng có thể trống. Tất cả các tài liệu giai đoạn phải khác không. See https. //www. mongodb. com/docs/manual/changeStreams/ để biết danh sách các giai đoạn quy trình có thể được sử dụng với các luồng thay đổi. Đối với một đường ống của bson. tài liệu D, mongo. Loại {} đường ống có thể được sử dụng

Tham số opts có thể được sử dụng để chỉ định các tùy chọn để tạo luồng thay đổi (xem các tùy chọn. ChangeStreamOptions tài liệu)

Thí dụ

collection := client.Database("baz").Collection("qux")
80
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

loại được thêm vào v1. 5. 0

collection := client.Database("baz").Collection("qux")
82

CollectionSpecification đại diện cho một bộ sưu tập trong cơ sở dữ liệu. Loại này được trả về bởi Cơ sở dữ liệu. Chức năng ListCollectionSpecifications

func (*CollectionSpecification) được thêm vào v1. 5. 0

collection := client.Database("baz").Collection("qux")
83

UnmarshalBSON triển khai bson. giao diện không thay đổi

loại được thêm vào v1. 0. 0

collection := client.Database("baz").Collection("qux")
84

CommandError biểu thị lỗi máy chủ trong khi thực thi lệnh. Điều này có thể được trả lại bởi bất kỳ hoạt động

func (Lỗi lệnh) được thêm vào v1. 0. 0

collection := client.Database("baz").Collection("qux")
85

Lỗi thực hiện giao diện lỗi

func (Lỗi lệnh) được thêm vào v1. 5. 0

collection := client.Database("baz").Collection("qux")
86

HasErrorCode trả về true nếu lỗi có mã được chỉ định

func (Lỗi lệnh) được thêm vào v1. 5. 0

collection := client.Database("baz").Collection("qux")
87

HasErrorCodeWithMessage trả về true nếu lỗi có mã được chỉ định và Tin nhắn chứa thông báo được chỉ định

func (Lỗi lệnh) được thêm vào v1. 0. 0

collection := client.Database("baz").Collection("qux")
88

HasErrorLabel trả về true nếu lỗi chứa nhãn đã chỉ định

func (Lỗi lệnh) được thêm vào v1. 5. 0

collection := client.Database("baz").Collection("qux")
89

HasErrorMessage trả về true nếu lỗi chứa thông báo đã chỉ định

func (Lỗi lệnh) được thêm vào v1. 1. 0

collection := client.Database("baz").Collection("qux")
90

IsMaxTimeMSExpiredError trả về true nếu lỗi là lỗi MaxTimeMSExpired

func (Lỗi lệnh) được thêm vào v1. 4. 0

collection := client.Database("baz").Collection("qux")
91

Unwrap trả về lỗi cơ bản

loại

collection := client.Database("baz").Collection("qux")
92

Con trỏ được sử dụng để lặp qua một luồng tài liệu. Mỗi tài liệu có thể được giải mã thành loại Go thông qua phương thức Giải mã hoặc được truy cập dưới dạng BSON thô thông qua trường Hiện tại. Loại này không an toàn cho goroutine và không được sử dụng đồng thời bởi nhiều goroutine

func được thêm vào v1. 9. 0

collection := client.Database("baz").Collection("qux")
93

NewCursorFromDocuments tạo một Con trỏ mới được tải sẵn các tài liệu, lỗi và sổ đăng ký được cung cấp. Nếu không có sổ đăng ký nào được cung cấp, bson. DefaultRegistry sẽ được sử dụng

Tham số tài liệu phải là một lát tài liệu. The slice may be nil or empty, but all elements must be non-nil

func (*Con trỏ) được thêm vào v1. 1. 0

collection := client.Database("baz").Collection("qux")
94

Tất cả lặp lại con trỏ và giải mã từng tài liệu thành kết quả. Tham số kết quả phải là một con trỏ tới một lát. Lát được chỉ ra bởi kết quả sẽ bị ghi đè hoàn toàn. Phương pháp này sẽ đóng con trỏ sau khi lấy tất cả các tài liệu. Nếu con trỏ đã được lặp lại, mọi tài liệu được lặp lại trước đó sẽ không được đưa vào kết quả

Phương pháp này yêu cầu phiên bản trình điều khiển >= 1. 1. 0

Thí dụ

collection := client.Database("baz").Collection("qux")
95
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

func (*Con trỏ) được thêm vào v0. 0. 2

collection := client.Database("baz").Collection("qux")
97

Đóng đóng con trỏ này. Next và TryNext không được gọi sau khi Close đã được gọi. Đóng là idempotent. Sau cuộc gọi đầu tiên, mọi cuộc gọi tiếp theo sẽ không thay đổi trạng thái

func (*Con trỏ) được thêm vào v0. 0. 2

collection := client.Database("baz").Collection("qux")
98

Giải mã sẽ sắp xếp lại tài liệu hiện tại thành val và trả về bất kỳ lỗi nào từ quá trình sắp xếp lại mà không có bất kỳ sửa đổi nào. Nếu val là nil hoặc là nil được nhập, một lỗi sẽ được trả về

func (*Con trỏ) được thêm vào v0. 0. 2

collection := client.Database("baz").Collection("qux")
99

Err trả về lỗi cuối cùng mà Con trỏ nhìn thấy hoặc không nếu không có lỗi xảy ra

func (*Con trỏ) được thêm vào v0. 0. 2

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
00

ID trả về ID của con trỏ này hoặc 0 nếu con trỏ đã được đóng hoặc hết

func (*Con trỏ) được thêm vào v0. 0. 2

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
01

Tiếp theo lấy tài liệu tiếp theo cho con trỏ này. Nó trả về true nếu không có lỗi và con trỏ chưa hết

Các khối tiếp theo cho đến khi có tài liệu, xảy ra lỗi hoặc ctx hết hạn. Nếu ctx hết hạn, lỗi sẽ được đặt thành ctx. Lỗi (). Trong trường hợp lỗi, Next sẽ trả về false

Nếu Next trả về false, các cuộc gọi tiếp theo cũng sẽ trả về false

Thí dụ

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
02____1_______0

Chia sẻ Định dạng Chạy

func (*Con trỏ) được thêm vào v1. 4. 0

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
04

RemainingBatchLength trả về số lượng tài liệu còn lại trong đợt hiện tại. Nếu giá trị này trả về 0, cuộc gọi tiếp theo tới Next hoặc TryNext sẽ thực hiện yêu cầu mạng để tìm nạp đợt tiếp theo

Thí dụ

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
05
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

func (*Con trỏ) được thêm vào v1. 2. 0

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
07

TryNext cố gắng lấy tài liệu tiếp theo cho con trỏ này. Nó trả về true nếu không có lỗi và tài liệu tiếp theo có sẵn. Điều này chỉ được khuyến nghị để sử dụng với các con trỏ có thể theo đuôi như một giải pháp thay thế không chặn cho Tiếp theo. Xem https. //www. mongodb. com/docs/manual/core/tailable-cursors/ để biết thêm thông tin về các con trỏ có thể điều chỉnh

TryNext trả về false nếu hết con trỏ, xảy ra lỗi khi nhận kết quả từ máy chủ, tài liệu tiếp theo chưa có sẵn hoặc ctx hết hạn. Nếu ctx hết hạn, lỗi sẽ được đặt thành ctx. Lỗi ()

Nếu TryNext trả về false và xảy ra lỗi hoặc con trỏ đã hết (i. e. c. Lỗi (). = không. c. ID() == 0), các lần thử tiếp theo cũng sẽ trả về false. Nếu không, bạn có thể gọi lại TryNext cho đến khi có tài liệu

Phương pháp này yêu cầu phiên bản trình điều khiển >= 1. 2. 0

Thí dụ

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
08
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

loại

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
10

Cơ sở dữ liệu là một xử lý cho cơ sở dữ liệu MongoDB. Nó an toàn để sử dụng đồng thời bởi nhiều goroutine

func (*Cơ sở dữ liệu) được thêm vào v1. 1. 0

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
11

Aggregate thực thi một lệnh tổng hợp cơ sở dữ liệu. Điều này yêu cầu phiên bản MongoDB >= 3. 6 và phiên bản trình điều khiển >= 1. 1. 0

Tham số đường ống phải là một lát tài liệu, mỗi phần đại diện cho một giai đoạn tổng hợp. Đường ống không thể là không nhưng có thể trống. Tất cả các tài liệu giai đoạn phải khác không. Đối với một đường ống của bson. tài liệu D, mongo. Loại đường ống có thể được sử dụng. Xem danh sách các giai đoạn hợp lệ trong tập hợp cấp cơ sở dữ liệu

Tham số opts có thể được sử dụng để chỉ định các tùy chọn cho thao tác này (xem các tùy chọn. Tài liệu tùy chọn tổng hợp)

Để biết thêm thông tin về lệnh, xem https. //www. mongodb. com/docs/manual/reference/command/aggregate/

func (*Cơ sở dữ liệu)

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
12

Máy khách trả về Máy khách Cơ sở dữ liệu được tạo từ

func (*Cơ sở dữ liệu)

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
13

Bộ sưu tập có một tay cầm cho một bộ sưu tập có tên đã cho được định cấu hình với CollectionOptions đã cho

func (*Cơ sở dữ liệu) được thêm vào v1. 4. 0

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
14

CreateCollection thực thi một lệnh tạo để tạo rõ ràng một bộ sưu tập mới với tên được chỉ định trên máy chủ. Nếu bộ sưu tập được tạo đã tồn tại, phương thức này sẽ trả về mongo. LệnhLỗi. Phương pháp này yêu cầu trình điều khiển phiên bản 1. 4. 0 hoặc cao hơn

Tham số opts có thể được sử dụng để chỉ định các tùy chọn cho hoạt động (xem các tùy chọn. CreateCollectionOptions tài liệu)

Để biết thêm thông tin về lệnh, xem https. //www. mongodb. com/docs/manual/reference/command/create/

Thí dụ

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
15
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

func (*Cơ sở dữ liệu) được thêm vào v1. 4. 0

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
17

CreateView thực thi lệnh tạo để tạo chế độ xem trên máy chủ một cách rõ ràng. Xem https. //www. mongodb. com/docs/manual/core/views/ để biết thêm thông tin về lượt xem. Phương pháp này yêu cầu phiên bản trình điều khiển >= 1. 4. 0 và phiên bản MongoDB >= 3. 4

Tham số viewName chỉ định tên của dạng xem để tạo

Tham số viewOn chỉ định tên của bộ sưu tập hoặc chế độ xem mà chế độ xem này sẽ được tạo

Tham số đường ống chỉ định một đường ống tổng hợp sẽ được thực thi đối với tập hợp nguồn hoặc dạng xem để tạo dạng xem này

Tham số opts có thể được sử dụng để chỉ định các tùy chọn cho hoạt động (xem các tùy chọn. Tài liệu CreateViewOptions)

Thí dụ

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
18
collection := client.Database("baz").Collection("qux")
0

Chia sẻ Định dạng Chạy

func (*Cơ sở dữ liệu) được thêm vào v0. 0. 4

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
20

Drop làm rơi cơ sở dữ liệu trên máy chủ. Phương pháp này bỏ qua các lỗi "không tìm thấy không gian tên" để có thể loại bỏ cơ sở dữ liệu không tồn tại trên máy chủ một cách an toàn

func (*Cơ sở dữ liệu) được thêm vào v1. 1. 0

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
21

ListCollectionNames thực thi lệnh listCollections và trả về một lát chứa tên của các bộ sưu tập trong cơ sở dữ liệu. Phương pháp này yêu cầu phiên bản trình điều khiển >= 1. 1. 0

Tham số bộ lọc phải là một tài liệu chứa toán tử truy vấn và có thể được sử dụng để chọn bộ sưu tập nào được đưa vào kết quả. Nó không thể là con số không. Một tài liệu trống (e. g. con trai. D{}) nên được sử dụng để bao gồm tất cả các bộ sưu tập

Tham số opts có thể được sử dụng để chỉ định các tùy chọn cho hoạt động (xem các tùy chọn. ListCollectionsOptions tài liệu)

Để biết thêm thông tin về lệnh, xem https. //www. mongodb. com/docs/manual/reference/command/listCollections/

LỖI (benjirewis). ListCollectionNames ngăn liệt kê hơn 100 bộ sưu tập trên mỗi cơ sở dữ liệu khi chạy với MongoDB phiên bản 2. 6

MongoDB insertOne là gì?

MongoDB cung cấp các phương thức sau để chèn tài liệu vào bộ sưu tập. insertOne() - Chèn một tài liệu vào bộ sưu tập . insert() - Chèn một hoặc nhiều tài liệu vào một bộ sưu tập. insertMany() - Chèn nhiều tài liệu vào một bộ sưu tập.

Làm cách nào để chèn một bản ghi trong MongoDB?

Trình vỏ MongoDB cung cấp các phương thức sau để chèn tài liệu vào bộ sưu tập. .
Để chèn một tài liệu, hãy sử dụng db. thu thập. chènMột ()
Để chèn nhiều tài liệu, hãy sử dụng db. thu thập. chènMany()

Sự khác biệt giữa insertOne và insertMany trong MongoDB là gì?

Với insertOne, bạn có thể chèn một tài liệu vào bộ sưu tập. insertMany chấp nhận một mảng tài liệu và chúng được chèn vào . Chèn (phương thức từ các phiên bản cũ hơn) theo mặc định lấy một tài liệu và có tùy chọn để chèn nhiều tài liệu được cung cấp dưới dạng một mảng.

Làm cách nào để sử dụng insertOne trong cầy mangut?

Sử dụng insertOne() trong Mongoose . const cầy mangut = yêu cầu('cầy mangut'); . Lược đồ ({ tên. Chuỗi }); . mô hình ('Kiểm tra', lược đồ); . Mongoose models do not have an insertOne() method, you should use the create() function instead. const mongoose = require('mongoose'); const schema = new mongoose. Schema({ name: String }); const TestModel = mongoose. model('Test', schema); async function run() { await mongoose.