-
Notifications
You must be signed in to change notification settings - Fork 0
/
insertmany.go
52 lines (40 loc) · 1.33 KB
/
insertmany.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package mongohelper
import (
"context"
"errors"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// InsertMany wraps the mongo.Database.Collection.InsertMany() method
// It returns an array with generated ObjectIDs and an error
func (l *Link) InsertMany(database, collection string, document []interface{}) ([]string, error) {
if err := l.linkCheck("link.InsertMany"); err != nil {
return []string{}, err
}
ctx, cancel := context.WithTimeout(context.Background(), l.execTimeout())
defer cancel()
rs, err := l.client.Database(database).Collection(collection).InsertMany(ctx, document, options.InsertMany())
if err != nil {
// If not connected, try once again
if errors.Is(err, mongo.ErrClientDisconnected) {
if err = l.connect(); err != nil {
return []string{}, err
}
ctx2, cancel2 := context.WithTimeout(context.Background(), l.execTimeout())
defer cancel2()
if rs, err = l.client.Database(database).Collection(collection).InsertMany(ctx2, document, options.InsertMany()); err != nil {
return []string{}, err
}
} else {
return []string{}, err
}
}
var oidHex []string
for _, o := range rs.InsertedIDs {
if oid, ok := o.(primitive.ObjectID); ok {
oidHex = append(oidHex, oid.Hex())
}
}
return oidHex, nil
}