bulk.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package mgo
  2. // Bulk represents an operation that can be prepared with several
  3. // orthogonal changes before being delivered to the server.
  4. //
  5. // WARNING: This API is still experimental.
  6. //
  7. // Relevant documentation:
  8. //
  9. // http://blog.mongodb.org/post/84922794768/mongodbs-new-bulk-api
  10. //
  11. type Bulk struct {
  12. c *Collection
  13. ordered bool
  14. inserts []interface{}
  15. }
  16. // BulkError holds an error returned from running a Bulk operation.
  17. //
  18. // TODO: This is private for the moment, until we understand exactly how
  19. // to report these multi-errors in a useful and convenient way.
  20. type bulkError struct {
  21. err error
  22. }
  23. // BulkResult holds the results for a bulk operation.
  24. type BulkResult struct {
  25. // Be conservative while we understand exactly how to report these
  26. // results in a useful and convenient way, and also how to emulate
  27. // them with prior servers.
  28. private bool
  29. }
  30. func (e *bulkError) Error() string {
  31. return e.err.Error()
  32. }
  33. // Bulk returns a value to prepare the execution of a bulk operation.
  34. //
  35. // WARNING: This API is still experimental.
  36. //
  37. func (c *Collection) Bulk() *Bulk {
  38. return &Bulk{c: c, ordered: true}
  39. }
  40. // Unordered puts the bulk operation in unordered mode.
  41. //
  42. // In unordered mode the indvidual operations may be sent
  43. // out of order, which means latter operations may proceed
  44. // even if prior ones have failed.
  45. func (b *Bulk) Unordered() {
  46. b.ordered = false
  47. }
  48. // Insert queues up the provided documents for insertion.
  49. func (b *Bulk) Insert(docs ...interface{}) {
  50. b.inserts = append(b.inserts, docs...)
  51. }
  52. // Run runs all the operations queued up.
  53. func (b *Bulk) Run() (*BulkResult, error) {
  54. op := &insertOp{b.c.FullName, b.inserts, 0}
  55. if !b.ordered {
  56. op.flags = 1 // ContinueOnError
  57. }
  58. _, err := b.c.writeQuery(op)
  59. if err != nil {
  60. return nil, &bulkError{err}
  61. }
  62. return &BulkResult{}, nil
  63. }