...

Source file src/go.mongodb.org/mongo-driver/mongo/writeconcern/writeconcern_example_test.go

Documentation: go.mongodb.org/mongo-driver/mongo/writeconcern

     1  // Copyright (C) MongoDB, Inc. 2023-present.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License"); you may
     4  // not use this file except in compliance with the License. You may obtain
     5  // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
     6  
     7  package writeconcern_test
     8  
     9  import (
    10  	"context"
    11  
    12  	"go.mongodb.org/mongo-driver/mongo"
    13  	"go.mongodb.org/mongo-driver/mongo/options"
    14  	"go.mongodb.org/mongo-driver/mongo/writeconcern"
    15  )
    16  
    17  // Configure a Client with write concern "majority" that requests
    18  // acknowledgement that a majority of the nodes have committed write operations.
    19  func Example_majority() {
    20  	wc := writeconcern.Majority()
    21  
    22  	opts := options.Client().
    23  		ApplyURI("mongodb://localhost:27017").
    24  		SetWriteConcern(wc)
    25  
    26  	_, err := mongo.Connect(context.Background(), opts)
    27  	if err != nil {
    28  		panic(err)
    29  	}
    30  }
    31  
    32  // Configure a Client with a write concern that requests acknowledgement that
    33  // exactly 2 nodes have committed and journaled write operations.
    34  func Example_w2Journaled() {
    35  	wc := &writeconcern.WriteConcern{
    36  		W:       2,
    37  		Journal: boolPtr(true),
    38  	}
    39  
    40  	opts := options.Client().
    41  		ApplyURI("mongodb://localhost:27017").
    42  		SetWriteConcern(wc)
    43  
    44  	_, err := mongo.Connect(context.Background(), opts)
    45  	if err != nil {
    46  		panic(err)
    47  	}
    48  }
    49  
    50  // boolPtr is a helper function to convert a bool constant into a bool pointer.
    51  //
    52  // If you're using a version of Go that supports generics, you can define a
    53  // generic version of this function that works with any type. For example:
    54  //
    55  //	func ptr[T any](v T) *T {
    56  //		return &v
    57  //	}
    58  func boolPtr(b bool) *bool {
    59  	return &b
    60  }
    61  

View as plain text