You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

collection.go 39 kB

4 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423
  1. // Copyright (C) MongoDB, Inc. 2017-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. package mongo
  7. import (
  8. "context"
  9. "errors"
  10. "fmt"
  11. "strings"
  12. "time"
  13. "go.mongodb.org/mongo-driver/bson"
  14. "go.mongodb.org/mongo-driver/bson/bsoncodec"
  15. "go.mongodb.org/mongo-driver/bson/bsontype"
  16. "go.mongodb.org/mongo-driver/mongo/options"
  17. "go.mongodb.org/mongo-driver/mongo/readconcern"
  18. "go.mongodb.org/mongo-driver/mongo/readpref"
  19. "go.mongodb.org/mongo-driver/mongo/writeconcern"
  20. "go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
  21. "go.mongodb.org/mongo-driver/x/mongo/driver"
  22. "go.mongodb.org/mongo-driver/x/mongo/driver/description"
  23. "go.mongodb.org/mongo-driver/x/mongo/driver/operation"
  24. "go.mongodb.org/mongo-driver/x/mongo/driver/session"
  25. )
  26. // Collection performs operations on a given collection.
  27. type Collection struct {
  28. client *Client
  29. db *Database
  30. name string
  31. readConcern *readconcern.ReadConcern
  32. writeConcern *writeconcern.WriteConcern
  33. readPreference *readpref.ReadPref
  34. readSelector description.ServerSelector
  35. writeSelector description.ServerSelector
  36. registry *bsoncodec.Registry
  37. }
  38. // aggregateParams is used to store information to configure an Aggregate operation.
  39. type aggregateParams struct {
  40. ctx context.Context
  41. pipeline interface{}
  42. client *Client
  43. registry *bsoncodec.Registry
  44. readConcern *readconcern.ReadConcern
  45. writeConcern *writeconcern.WriteConcern
  46. retryRead bool
  47. db string
  48. col string
  49. readSelector description.ServerSelector
  50. writeSelector description.ServerSelector
  51. readPreference *readpref.ReadPref
  52. opts []*options.AggregateOptions
  53. }
  54. func closeImplicitSession(sess *session.Client) {
  55. if sess != nil && sess.SessionType == session.Implicit {
  56. sess.EndSession()
  57. }
  58. }
  59. func newCollection(db *Database, name string, opts ...*options.CollectionOptions) *Collection {
  60. collOpt := options.MergeCollectionOptions(opts...)
  61. rc := db.readConcern
  62. if collOpt.ReadConcern != nil {
  63. rc = collOpt.ReadConcern
  64. }
  65. wc := db.writeConcern
  66. if collOpt.WriteConcern != nil {
  67. wc = collOpt.WriteConcern
  68. }
  69. rp := db.readPreference
  70. if collOpt.ReadPreference != nil {
  71. rp = collOpt.ReadPreference
  72. }
  73. reg := db.registry
  74. if collOpt.Registry != nil {
  75. reg = collOpt.Registry
  76. }
  77. readSelector := description.CompositeSelector([]description.ServerSelector{
  78. description.ReadPrefSelector(rp),
  79. description.LatencySelector(db.client.localThreshold),
  80. })
  81. writeSelector := description.CompositeSelector([]description.ServerSelector{
  82. description.WriteSelector(),
  83. description.LatencySelector(db.client.localThreshold),
  84. })
  85. coll := &Collection{
  86. client: db.client,
  87. db: db,
  88. name: name,
  89. readPreference: rp,
  90. readConcern: rc,
  91. writeConcern: wc,
  92. readSelector: readSelector,
  93. writeSelector: writeSelector,
  94. registry: reg,
  95. }
  96. return coll
  97. }
  98. func (coll *Collection) copy() *Collection {
  99. return &Collection{
  100. client: coll.client,
  101. db: coll.db,
  102. name: coll.name,
  103. readConcern: coll.readConcern,
  104. writeConcern: coll.writeConcern,
  105. readPreference: coll.readPreference,
  106. readSelector: coll.readSelector,
  107. writeSelector: coll.writeSelector,
  108. registry: coll.registry,
  109. }
  110. }
  111. // Clone creates a copy of this collection with updated options, if any are given.
  112. func (coll *Collection) Clone(opts ...*options.CollectionOptions) (*Collection, error) {
  113. copyColl := coll.copy()
  114. optsColl := options.MergeCollectionOptions(opts...)
  115. if optsColl.ReadConcern != nil {
  116. copyColl.readConcern = optsColl.ReadConcern
  117. }
  118. if optsColl.WriteConcern != nil {
  119. copyColl.writeConcern = optsColl.WriteConcern
  120. }
  121. if optsColl.ReadPreference != nil {
  122. copyColl.readPreference = optsColl.ReadPreference
  123. }
  124. if optsColl.Registry != nil {
  125. copyColl.registry = optsColl.Registry
  126. }
  127. copyColl.readSelector = description.CompositeSelector([]description.ServerSelector{
  128. description.ReadPrefSelector(copyColl.readPreference),
  129. description.LatencySelector(copyColl.client.localThreshold),
  130. })
  131. return copyColl, nil
  132. }
  133. // Name provides access to the name of the collection.
  134. func (coll *Collection) Name() string {
  135. return coll.name
  136. }
  137. // Database provides access to the database that contains the collection.
  138. func (coll *Collection) Database() *Database {
  139. return coll.db
  140. }
  141. // BulkWrite performs a bulk write operation.
  142. //
  143. // See https://docs.mongodb.com/manual/core/bulk-write-operations/.
  144. func (coll *Collection) BulkWrite(ctx context.Context, models []WriteModel,
  145. opts ...*options.BulkWriteOptions) (*BulkWriteResult, error) {
  146. if len(models) == 0 {
  147. return nil, ErrEmptySlice
  148. }
  149. if ctx == nil {
  150. ctx = context.Background()
  151. }
  152. sess := sessionFromContext(ctx)
  153. if sess == nil && coll.client.topology.SessionPool != nil {
  154. sess, err := session.NewClientSession(coll.client.topology.SessionPool, coll.client.id, session.Implicit)
  155. if err != nil {
  156. return nil, err
  157. }
  158. defer sess.EndSession()
  159. }
  160. err := coll.client.validSession(sess)
  161. if err != nil {
  162. return nil, err
  163. }
  164. wc := coll.writeConcern
  165. if sess.TransactionRunning() {
  166. wc = nil
  167. }
  168. if !writeconcern.AckWrite(wc) {
  169. sess = nil
  170. }
  171. selector := makePinnedSelector(sess, coll.writeSelector)
  172. for _, model := range models {
  173. if model == nil {
  174. return nil, ErrNilDocument
  175. }
  176. }
  177. bwo := options.MergeBulkWriteOptions(opts...)
  178. op := bulkWrite{
  179. ordered: bwo.Ordered,
  180. bypassDocumentValidation: bwo.BypassDocumentValidation,
  181. models: models,
  182. session: sess,
  183. collection: coll,
  184. selector: selector,
  185. writeConcern: wc,
  186. }
  187. err = op.execute(ctx)
  188. return &op.result, replaceErrors(err)
  189. }
  190. func (coll *Collection) insert(ctx context.Context, documents []interface{},
  191. opts ...*options.InsertManyOptions) ([]interface{}, error) {
  192. if ctx == nil {
  193. ctx = context.Background()
  194. }
  195. result := make([]interface{}, len(documents))
  196. docs := make([]bsoncore.Document, len(documents))
  197. for i, doc := range documents {
  198. var err error
  199. docs[i], result[i], err = transformAndEnsureIDv2(coll.registry, doc)
  200. if err != nil {
  201. return nil, err
  202. }
  203. }
  204. sess := sessionFromContext(ctx)
  205. if sess == nil && coll.client.topology.SessionPool != nil {
  206. var err error
  207. sess, err = session.NewClientSession(coll.client.topology.SessionPool, coll.client.id, session.Implicit)
  208. if err != nil {
  209. return nil, err
  210. }
  211. defer sess.EndSession()
  212. }
  213. err := coll.client.validSession(sess)
  214. if err != nil {
  215. return nil, err
  216. }
  217. wc := coll.writeConcern
  218. if sess.TransactionRunning() {
  219. wc = nil
  220. }
  221. if !writeconcern.AckWrite(wc) {
  222. sess = nil
  223. }
  224. selector := makePinnedSelector(sess, coll.writeSelector)
  225. op := operation.NewInsert(docs...).
  226. Session(sess).WriteConcern(wc).CommandMonitor(coll.client.monitor).
  227. ServerSelector(selector).ClusterClock(coll.client.clock).
  228. Database(coll.db.name).Collection(coll.name).
  229. Deployment(coll.client.topology)
  230. imo := options.MergeInsertManyOptions(opts...)
  231. if imo.BypassDocumentValidation != nil && *imo.BypassDocumentValidation {
  232. op = op.BypassDocumentValidation(*imo.BypassDocumentValidation)
  233. }
  234. if imo.Ordered != nil {
  235. op = op.Ordered(*imo.Ordered)
  236. }
  237. retry := driver.RetryNone
  238. if coll.client.retryWrites {
  239. retry = driver.RetryOncePerCommand
  240. }
  241. op = op.Retry(retry)
  242. return result, op.Execute(ctx)
  243. }
  244. // InsertOne inserts a single document into the collection.
  245. func (coll *Collection) InsertOne(ctx context.Context, document interface{},
  246. opts ...*options.InsertOneOptions) (*InsertOneResult, error) {
  247. imOpts := make([]*options.InsertManyOptions, len(opts))
  248. for i, opt := range opts {
  249. imo := options.InsertMany()
  250. if opt.BypassDocumentValidation != nil && *opt.BypassDocumentValidation {
  251. imo = imo.SetBypassDocumentValidation(*opt.BypassDocumentValidation)
  252. }
  253. imOpts[i] = imo
  254. }
  255. res, err := coll.insert(ctx, []interface{}{document}, imOpts...)
  256. rr, err := processWriteError(err)
  257. if rr&rrOne == 0 {
  258. return nil, err
  259. }
  260. return &InsertOneResult{InsertedID: res[0]}, err
  261. }
  262. // InsertMany inserts the provided documents.
  263. func (coll *Collection) InsertMany(ctx context.Context, documents []interface{},
  264. opts ...*options.InsertManyOptions) (*InsertManyResult, error) {
  265. if len(documents) == 0 {
  266. return nil, ErrEmptySlice
  267. }
  268. result, err := coll.insert(ctx, documents, opts...)
  269. rr, err := processWriteError(err)
  270. if rr&rrMany == 0 {
  271. return nil, err
  272. }
  273. imResult := &InsertManyResult{InsertedIDs: result}
  274. writeException, ok := err.(WriteException)
  275. if !ok {
  276. return imResult, err
  277. }
  278. // create and return a BulkWriteException
  279. bwErrors := make([]BulkWriteError, 0, len(writeException.WriteErrors))
  280. for _, we := range writeException.WriteErrors {
  281. bwErrors = append(bwErrors, BulkWriteError{
  282. WriteError{
  283. Index: we.Index,
  284. Code: we.Code,
  285. Message: we.Message,
  286. },
  287. nil,
  288. })
  289. }
  290. return imResult, BulkWriteException{
  291. WriteErrors: bwErrors,
  292. WriteConcernError: writeException.WriteConcernError,
  293. }
  294. }
  295. func (coll *Collection) delete(ctx context.Context, filter interface{}, deleteOne bool, expectedRr returnResult,
  296. opts ...*options.DeleteOptions) (*DeleteResult, error) {
  297. if ctx == nil {
  298. ctx = context.Background()
  299. }
  300. f, err := transformBsoncoreDocument(coll.registry, filter)
  301. if err != nil {
  302. return nil, err
  303. }
  304. sess := sessionFromContext(ctx)
  305. if sess == nil && coll.client.topology.SessionPool != nil {
  306. sess, err = session.NewClientSession(coll.client.topology.SessionPool, coll.client.id, session.Implicit)
  307. if err != nil {
  308. return nil, err
  309. }
  310. defer sess.EndSession()
  311. }
  312. err = coll.client.validSession(sess)
  313. if err != nil {
  314. return nil, err
  315. }
  316. wc := coll.writeConcern
  317. if sess.TransactionRunning() {
  318. wc = nil
  319. }
  320. if !writeconcern.AckWrite(wc) {
  321. sess = nil
  322. }
  323. selector := makePinnedSelector(sess, coll.writeSelector)
  324. var limit int32
  325. if deleteOne {
  326. limit = 1
  327. }
  328. do := options.MergeDeleteOptions(opts...)
  329. didx, doc := bsoncore.AppendDocumentStart(nil)
  330. doc = bsoncore.AppendDocumentElement(doc, "q", f)
  331. doc = bsoncore.AppendInt32Element(doc, "limit", limit)
  332. if do.Collation != nil {
  333. doc = bsoncore.AppendDocumentElement(doc, "collation", do.Collation.ToDocument())
  334. }
  335. doc, _ = bsoncore.AppendDocumentEnd(doc, didx)
  336. op := operation.NewDelete(doc).
  337. Session(sess).WriteConcern(wc).CommandMonitor(coll.client.monitor).
  338. ServerSelector(selector).ClusterClock(coll.client.clock).
  339. Database(coll.db.name).Collection(coll.name).
  340. Deployment(coll.client.topology)
  341. // deleteMany cannot be retried
  342. retryMode := driver.RetryNone
  343. if deleteOne && coll.client.retryWrites {
  344. retryMode = driver.RetryOncePerCommand
  345. }
  346. op = op.Retry(retryMode)
  347. rr, err := processWriteError(op.Execute(ctx))
  348. if rr&expectedRr == 0 {
  349. return nil, err
  350. }
  351. return &DeleteResult{DeletedCount: int64(op.Result().N)}, err
  352. }
  353. // DeleteOne deletes a single document from the collection.
  354. func (coll *Collection) DeleteOne(ctx context.Context, filter interface{},
  355. opts ...*options.DeleteOptions) (*DeleteResult, error) {
  356. return coll.delete(ctx, filter, true, rrOne, opts...)
  357. }
  358. // DeleteMany deletes multiple documents from the collection.
  359. func (coll *Collection) DeleteMany(ctx context.Context, filter interface{},
  360. opts ...*options.DeleteOptions) (*DeleteResult, error) {
  361. return coll.delete(ctx, filter, false, rrMany, opts...)
  362. }
  363. func (coll *Collection) updateOrReplace(ctx context.Context, filter bsoncore.Document, update interface{}, multi bool,
  364. expectedRr returnResult, checkDollarKey bool, opts ...*options.UpdateOptions) (*UpdateResult, error) {
  365. if ctx == nil {
  366. ctx = context.Background()
  367. }
  368. uo := options.MergeUpdateOptions(opts...)
  369. uidx, updateDoc := bsoncore.AppendDocumentStart(nil)
  370. updateDoc = bsoncore.AppendDocumentElement(updateDoc, "q", filter)
  371. u, err := transformUpdateValue(coll.registry, update, checkDollarKey)
  372. if err != nil {
  373. return nil, err
  374. }
  375. updateDoc = bsoncore.AppendValueElement(updateDoc, "u", u)
  376. if multi {
  377. updateDoc = bsoncore.AppendBooleanElement(updateDoc, "multi", multi)
  378. }
  379. // collation, arrayFilters, and upsert are included on the individual update documents rather than as part of the
  380. // command
  381. if uo.Collation != nil {
  382. updateDoc = bsoncore.AppendDocumentElement(updateDoc, "collation", bsoncore.Document(uo.Collation.ToDocument()))
  383. }
  384. if uo.ArrayFilters != nil {
  385. arr, err := uo.ArrayFilters.ToArrayDocument()
  386. if err != nil {
  387. return nil, err
  388. }
  389. updateDoc = bsoncore.AppendArrayElement(updateDoc, "arrayFilters", arr)
  390. }
  391. if uo.Upsert != nil {
  392. updateDoc = bsoncore.AppendBooleanElement(updateDoc, "upsert", *uo.Upsert)
  393. }
  394. updateDoc, _ = bsoncore.AppendDocumentEnd(updateDoc, uidx)
  395. sess := sessionFromContext(ctx)
  396. if sess == nil && coll.client.topology.SessionPool != nil {
  397. var err error
  398. sess, err = session.NewClientSession(coll.client.topology.SessionPool, coll.client.id, session.Implicit)
  399. if err != nil {
  400. return nil, err
  401. }
  402. defer sess.EndSession()
  403. }
  404. err = coll.client.validSession(sess)
  405. if err != nil {
  406. return nil, err
  407. }
  408. wc := coll.writeConcern
  409. if sess.TransactionRunning() {
  410. wc = nil
  411. }
  412. if !writeconcern.AckWrite(wc) {
  413. sess = nil
  414. }
  415. selector := makePinnedSelector(sess, coll.writeSelector)
  416. op := operation.NewUpdate(updateDoc).
  417. Session(sess).WriteConcern(wc).CommandMonitor(coll.client.monitor).
  418. ServerSelector(selector).ClusterClock(coll.client.clock).
  419. Database(coll.db.name).Collection(coll.name).
  420. Deployment(coll.client.topology)
  421. if uo.BypassDocumentValidation != nil && *uo.BypassDocumentValidation {
  422. op = op.BypassDocumentValidation(*uo.BypassDocumentValidation)
  423. }
  424. retry := driver.RetryNone
  425. // retryable writes are only enabled updateOne/replaceOne operations
  426. if !multi && coll.client.retryWrites {
  427. retry = driver.RetryOncePerCommand
  428. }
  429. op = op.Retry(retry)
  430. err = op.Execute(ctx)
  431. rr, err := processWriteError(err)
  432. if rr&expectedRr == 0 {
  433. return nil, err
  434. }
  435. opRes := op.Result()
  436. res := &UpdateResult{
  437. MatchedCount: int64(opRes.N),
  438. ModifiedCount: int64(opRes.NModified),
  439. UpsertedCount: int64(len(opRes.Upserted)),
  440. }
  441. if len(opRes.Upserted) > 0 {
  442. res.UpsertedID = opRes.Upserted[0].ID
  443. res.MatchedCount--
  444. }
  445. return res, err
  446. }
  447. // UpdateOne updates a single document in the collection.
  448. func (coll *Collection) UpdateOne(ctx context.Context, filter interface{}, update interface{},
  449. opts ...*options.UpdateOptions) (*UpdateResult, error) {
  450. if ctx == nil {
  451. ctx = context.Background()
  452. }
  453. f, err := transformBsoncoreDocument(coll.registry, filter)
  454. if err != nil {
  455. return nil, err
  456. }
  457. return coll.updateOrReplace(ctx, f, update, false, rrOne, true, opts...)
  458. }
  459. // UpdateMany updates multiple documents in the collection.
  460. func (coll *Collection) UpdateMany(ctx context.Context, filter interface{}, update interface{},
  461. opts ...*options.UpdateOptions) (*UpdateResult, error) {
  462. if ctx == nil {
  463. ctx = context.Background()
  464. }
  465. f, err := transformBsoncoreDocument(coll.registry, filter)
  466. if err != nil {
  467. return nil, err
  468. }
  469. return coll.updateOrReplace(ctx, f, update, true, rrMany, true, opts...)
  470. }
  471. // ReplaceOne replaces a single document in the collection.
  472. func (coll *Collection) ReplaceOne(ctx context.Context, filter interface{},
  473. replacement interface{}, opts ...*options.ReplaceOptions) (*UpdateResult, error) {
  474. if ctx == nil {
  475. ctx = context.Background()
  476. }
  477. f, err := transformBsoncoreDocument(coll.registry, filter)
  478. if err != nil {
  479. return nil, err
  480. }
  481. r, err := transformBsoncoreDocument(coll.registry, replacement)
  482. if err != nil {
  483. return nil, err
  484. }
  485. if elem, err := r.IndexErr(0); err == nil && strings.HasPrefix(elem.Key(), "$") {
  486. return nil, errors.New("replacement document cannot contains keys beginning with '$")
  487. }
  488. updateOptions := make([]*options.UpdateOptions, 0, len(opts))
  489. for _, opt := range opts {
  490. uOpts := options.Update()
  491. uOpts.BypassDocumentValidation = opt.BypassDocumentValidation
  492. uOpts.Collation = opt.Collation
  493. uOpts.Upsert = opt.Upsert
  494. updateOptions = append(updateOptions, uOpts)
  495. }
  496. return coll.updateOrReplace(ctx, f, r, false, rrOne, false, updateOptions...)
  497. }
  498. // Aggregate runs an aggregation framework pipeline.
  499. //
  500. // See https://docs.mongodb.com/manual/aggregation/.
  501. func (coll *Collection) Aggregate(ctx context.Context, pipeline interface{},
  502. opts ...*options.AggregateOptions) (*Cursor, error) {
  503. a := aggregateParams{
  504. ctx: ctx,
  505. pipeline: pipeline,
  506. client: coll.client,
  507. registry: coll.registry,
  508. readConcern: coll.readConcern,
  509. writeConcern: coll.writeConcern,
  510. retryRead: coll.client.retryReads,
  511. db: coll.db.name,
  512. col: coll.name,
  513. readSelector: coll.readSelector,
  514. writeSelector: coll.writeSelector,
  515. readPreference: coll.readPreference,
  516. opts: opts,
  517. }
  518. return aggregate(a)
  519. }
  520. // aggreate is the helper method for Aggregate
  521. func aggregate(a aggregateParams) (*Cursor, error) {
  522. if a.ctx == nil {
  523. a.ctx = context.Background()
  524. }
  525. pipelineArr, hasOutputStage, err := transformAggregatePipelinev2(a.registry, a.pipeline)
  526. if err != nil {
  527. return nil, err
  528. }
  529. sess := sessionFromContext(a.ctx)
  530. if sess == nil && a.client.topology.SessionPool != nil {
  531. sess, err = session.NewClientSession(a.client.topology.SessionPool, a.client.id, session.Implicit)
  532. if err != nil {
  533. return nil, err
  534. }
  535. }
  536. if err = a.client.validSession(sess); err != nil {
  537. return nil, err
  538. }
  539. var wc *writeconcern.WriteConcern
  540. if hasOutputStage {
  541. wc = a.writeConcern
  542. }
  543. rc := a.readConcern
  544. if sess.TransactionRunning() {
  545. wc = nil
  546. rc = nil
  547. }
  548. if !writeconcern.AckWrite(wc) {
  549. closeImplicitSession(sess)
  550. sess = nil
  551. }
  552. defaultSelector := a.readSelector
  553. if hasOutputStage {
  554. defaultSelector = a.writeSelector
  555. }
  556. selector := makePinnedSelector(sess, defaultSelector)
  557. ao := options.MergeAggregateOptions(a.opts...)
  558. cursorOpts := driver.CursorOptions{
  559. CommandMonitor: a.client.monitor,
  560. }
  561. op := operation.NewAggregate(pipelineArr).Session(sess).WriteConcern(wc).ReadConcern(rc).ReadPreference(a.readPreference).CommandMonitor(a.client.monitor).
  562. ServerSelector(selector).ClusterClock(a.client.clock).Database(a.db).Collection(a.col).Deployment(a.client.topology)
  563. if ao.AllowDiskUse != nil {
  564. op.AllowDiskUse(*ao.AllowDiskUse)
  565. }
  566. // ignore batchSize of 0 with $out
  567. if ao.BatchSize != nil && !(*ao.BatchSize == 0 && hasOutputStage) {
  568. op.BatchSize(*ao.BatchSize)
  569. cursorOpts.BatchSize = *ao.BatchSize
  570. }
  571. if ao.BypassDocumentValidation != nil && *ao.BypassDocumentValidation {
  572. op.BypassDocumentValidation(*ao.BypassDocumentValidation)
  573. }
  574. if ao.Collation != nil {
  575. op.Collation(bsoncore.Document(ao.Collation.ToDocument()))
  576. }
  577. if ao.MaxTime != nil {
  578. op.MaxTimeMS(int64(*ao.MaxTime / time.Millisecond))
  579. }
  580. if ao.MaxAwaitTime != nil {
  581. cursorOpts.MaxTimeMS = int64(*ao.MaxAwaitTime / time.Millisecond)
  582. }
  583. if ao.Comment != nil {
  584. op.Comment(*ao.Comment)
  585. }
  586. if ao.Hint != nil {
  587. hintVal, err := transformValue(a.registry, ao.Hint)
  588. if err != nil {
  589. closeImplicitSession(sess)
  590. return nil, err
  591. }
  592. op.Hint(hintVal)
  593. }
  594. retry := driver.RetryNone
  595. if a.retryRead && !hasOutputStage {
  596. retry = driver.RetryOncePerCommand
  597. }
  598. op = op.Retry(retry)
  599. err = op.Execute(a.ctx)
  600. if err != nil {
  601. closeImplicitSession(sess)
  602. if wce, ok := err.(driver.WriteCommandError); ok && wce.WriteConcernError != nil {
  603. return nil, *convertDriverWriteConcernError(wce.WriteConcernError)
  604. }
  605. return nil, replaceErrors(err)
  606. }
  607. bc, err := op.Result(cursorOpts)
  608. if err != nil {
  609. closeImplicitSession(sess)
  610. return nil, replaceErrors(err)
  611. }
  612. cursor, err := newCursorWithSession(bc, a.registry, sess)
  613. return cursor, replaceErrors(err)
  614. }
  615. // CountDocuments gets the number of documents matching the filter.
  616. // For a fast count of the total documents in a collection see EstimatedDocumentCount.
  617. func (coll *Collection) CountDocuments(ctx context.Context, filter interface{},
  618. opts ...*options.CountOptions) (int64, error) {
  619. if ctx == nil {
  620. ctx = context.Background()
  621. }
  622. countOpts := options.MergeCountOptions(opts...)
  623. pipelineArr, err := countDocumentsAggregatePipeline(coll.registry, filter, countOpts)
  624. if err != nil {
  625. return 0, err
  626. }
  627. sess := sessionFromContext(ctx)
  628. if sess == nil && coll.client.topology.SessionPool != nil {
  629. sess, err = session.NewClientSession(coll.client.topology.SessionPool, coll.client.id, session.Implicit)
  630. if err != nil {
  631. return 0, err
  632. }
  633. defer sess.EndSession()
  634. }
  635. if err = coll.client.validSession(sess); err != nil {
  636. return 0, err
  637. }
  638. rc := coll.readConcern
  639. if sess.TransactionRunning() {
  640. rc = nil
  641. }
  642. selector := makePinnedSelector(sess, coll.readSelector)
  643. op := operation.NewAggregate(pipelineArr).Session(sess).ReadConcern(rc).ReadPreference(coll.readPreference).
  644. CommandMonitor(coll.client.monitor).ServerSelector(selector).ClusterClock(coll.client.clock).Database(coll.db.name).
  645. Collection(coll.name).Deployment(coll.client.topology)
  646. if countOpts.Collation != nil {
  647. op.Collation(bsoncore.Document(countOpts.Collation.ToDocument()))
  648. }
  649. if countOpts.MaxTime != nil {
  650. op.MaxTimeMS(int64(*countOpts.MaxTime / time.Millisecond))
  651. }
  652. if countOpts.Hint != nil {
  653. hintVal, err := transformValue(coll.registry, countOpts.Hint)
  654. if err != nil {
  655. return 0, err
  656. }
  657. op.Hint(hintVal)
  658. }
  659. retry := driver.RetryNone
  660. if coll.client.retryReads {
  661. retry = driver.RetryOncePerCommand
  662. }
  663. op = op.Retry(retry)
  664. err = op.Execute(ctx)
  665. if err != nil {
  666. return 0, replaceErrors(err)
  667. }
  668. batch := op.ResultCursorResponse().FirstBatch
  669. if batch == nil {
  670. return 0, errors.New("invalid response from server, no 'firstBatch' field")
  671. }
  672. docs, err := batch.Documents()
  673. if err != nil || len(docs) == 0 {
  674. return 0, nil
  675. }
  676. val, ok := docs[0].Lookup("n").AsInt64OK()
  677. if !ok {
  678. return 0, errors.New("invalid response from server, no 'n' field")
  679. }
  680. return val, nil
  681. }
  682. // EstimatedDocumentCount gets an estimate of the count of documents in a collection using collection metadata.
  683. func (coll *Collection) EstimatedDocumentCount(ctx context.Context,
  684. opts ...*options.EstimatedDocumentCountOptions) (int64, error) {
  685. if ctx == nil {
  686. ctx = context.Background()
  687. }
  688. sess := sessionFromContext(ctx)
  689. var err error
  690. if sess == nil && coll.client.topology.SessionPool != nil {
  691. sess, err = session.NewClientSession(coll.client.topology.SessionPool, coll.client.id, session.Implicit)
  692. if err != nil {
  693. return 0, err
  694. }
  695. defer sess.EndSession()
  696. }
  697. err = coll.client.validSession(sess)
  698. if err != nil {
  699. return 0, err
  700. }
  701. rc := coll.readConcern
  702. if sess.TransactionRunning() {
  703. rc = nil
  704. }
  705. selector := makePinnedSelector(sess, coll.readSelector)
  706. op := operation.NewCount().Session(sess).ClusterClock(coll.client.clock).
  707. Database(coll.db.name).Collection(coll.name).CommandMonitor(coll.client.monitor).
  708. Deployment(coll.client.topology).ReadConcern(rc).ReadPreference(coll.readPreference).
  709. ServerSelector(selector)
  710. co := options.MergeEstimatedDocumentCountOptions(opts...)
  711. if co.MaxTime != nil {
  712. op = op.MaxTimeMS(int64(*co.MaxTime / time.Millisecond))
  713. }
  714. retry := driver.RetryNone
  715. if coll.client.retryReads {
  716. retry = driver.RetryOncePerCommand
  717. }
  718. op.Retry(retry)
  719. err = op.Execute(ctx)
  720. return op.Result().N, replaceErrors(err)
  721. }
  722. // Distinct finds the distinct values for a specified field across a single
  723. // collection.
  724. func (coll *Collection) Distinct(ctx context.Context, fieldName string, filter interface{},
  725. opts ...*options.DistinctOptions) ([]interface{}, error) {
  726. if ctx == nil {
  727. ctx = context.Background()
  728. }
  729. f, err := transformBsoncoreDocument(coll.registry, filter)
  730. if err != nil {
  731. return nil, err
  732. }
  733. sess := sessionFromContext(ctx)
  734. if sess == nil && coll.client.topology.SessionPool != nil {
  735. sess, err = session.NewClientSession(coll.client.topology.SessionPool, coll.client.id, session.Implicit)
  736. if err != nil {
  737. return nil, err
  738. }
  739. defer sess.EndSession()
  740. }
  741. err = coll.client.validSession(sess)
  742. if err != nil {
  743. return nil, err
  744. }
  745. rc := coll.readConcern
  746. if sess.TransactionRunning() {
  747. rc = nil
  748. }
  749. selector := makePinnedSelector(sess, coll.readSelector)
  750. option := options.MergeDistinctOptions(opts...)
  751. op := operation.NewDistinct(fieldName, bsoncore.Document(f)).
  752. Session(sess).ClusterClock(coll.client.clock).
  753. Database(coll.db.name).Collection(coll.name).CommandMonitor(coll.client.monitor).
  754. Deployment(coll.client.topology).ReadConcern(rc).ReadPreference(coll.readPreference).
  755. ServerSelector(selector)
  756. if option.Collation != nil {
  757. op.Collation(bsoncore.Document(option.Collation.ToDocument()))
  758. }
  759. if option.MaxTime != nil {
  760. op.MaxTimeMS(int64(*option.MaxTime / time.Millisecond))
  761. }
  762. retry := driver.RetryNone
  763. if coll.client.retryReads {
  764. retry = driver.RetryOncePerCommand
  765. }
  766. op = op.Retry(retry)
  767. err = op.Execute(ctx)
  768. if err != nil {
  769. return nil, replaceErrors(err)
  770. }
  771. arr, ok := op.Result().Values.ArrayOK()
  772. if !ok {
  773. return nil, fmt.Errorf("response field 'values' is type array, but received BSON type %s", op.Result().Values.Type)
  774. }
  775. values, err := arr.Values()
  776. if err != nil {
  777. return nil, err
  778. }
  779. retArray := make([]interface{}, len(values))
  780. for i, val := range values {
  781. raw := bson.RawValue{Type: val.Type, Value: val.Data}
  782. err = raw.Unmarshal(&retArray[i])
  783. if err != nil {
  784. return nil, err
  785. }
  786. }
  787. return retArray, replaceErrors(err)
  788. }
  789. // Find finds the documents matching a model.
  790. func (coll *Collection) Find(ctx context.Context, filter interface{},
  791. opts ...*options.FindOptions) (*Cursor, error) {
  792. if ctx == nil {
  793. ctx = context.Background()
  794. }
  795. f, err := transformBsoncoreDocument(coll.registry, filter)
  796. if err != nil {
  797. return nil, err
  798. }
  799. sess := sessionFromContext(ctx)
  800. if sess == nil && coll.client.topology.SessionPool != nil {
  801. var err error
  802. sess, err = session.NewClientSession(coll.client.topology.SessionPool, coll.client.id, session.Implicit)
  803. if err != nil {
  804. return nil, err
  805. }
  806. }
  807. err = coll.client.validSession(sess)
  808. if err != nil {
  809. closeImplicitSession(sess)
  810. return nil, err
  811. }
  812. rc := coll.readConcern
  813. if sess.TransactionRunning() {
  814. rc = nil
  815. }
  816. selector := makePinnedSelector(sess, coll.readSelector)
  817. op := operation.NewFind(f).
  818. Session(sess).ReadConcern(rc).ReadPreference(coll.readPreference).
  819. CommandMonitor(coll.client.monitor).ServerSelector(selector).
  820. ClusterClock(coll.client.clock).Database(coll.db.name).Collection(coll.name).
  821. Deployment(coll.client.topology)
  822. fo := options.MergeFindOptions(opts...)
  823. cursorOpts := driver.CursorOptions{
  824. CommandMonitor: coll.client.monitor,
  825. }
  826. if fo.AllowPartialResults != nil {
  827. op.AllowPartialResults(*fo.AllowPartialResults)
  828. }
  829. if fo.BatchSize != nil {
  830. cursorOpts.BatchSize = *fo.BatchSize
  831. op.BatchSize(*fo.BatchSize)
  832. }
  833. if fo.Collation != nil {
  834. op.Collation(bsoncore.Document(fo.Collation.ToDocument()))
  835. }
  836. if fo.Comment != nil {
  837. op.Comment(*fo.Comment)
  838. }
  839. if fo.CursorType != nil {
  840. switch *fo.CursorType {
  841. case options.Tailable:
  842. op.Tailable(true)
  843. case options.TailableAwait:
  844. op.Tailable(true)
  845. op.AwaitData(true)
  846. }
  847. }
  848. if fo.Hint != nil {
  849. hint, err := transformValue(coll.registry, fo.Hint)
  850. if err != nil {
  851. closeImplicitSession(sess)
  852. return nil, err
  853. }
  854. op.Hint(hint)
  855. }
  856. if fo.Limit != nil {
  857. limit := *fo.Limit
  858. if limit < 0 {
  859. limit = -1 * limit
  860. op.SingleBatch(true)
  861. }
  862. cursorOpts.Limit = int32(limit)
  863. op.Limit(limit)
  864. }
  865. if fo.Max != nil {
  866. max, err := transformBsoncoreDocument(coll.registry, fo.Max)
  867. if err != nil {
  868. closeImplicitSession(sess)
  869. return nil, err
  870. }
  871. op.Max(max)
  872. }
  873. if fo.MaxAwaitTime != nil {
  874. cursorOpts.MaxTimeMS = int64(*fo.MaxAwaitTime / time.Millisecond)
  875. }
  876. if fo.MaxTime != nil {
  877. op.MaxTimeMS(int64(*fo.MaxTime / time.Millisecond))
  878. }
  879. if fo.Min != nil {
  880. min, err := transformBsoncoreDocument(coll.registry, fo.Min)
  881. if err != nil {
  882. closeImplicitSession(sess)
  883. return nil, err
  884. }
  885. op.Min(min)
  886. }
  887. if fo.NoCursorTimeout != nil {
  888. op.NoCursorTimeout(*fo.NoCursorTimeout)
  889. }
  890. if fo.OplogReplay != nil {
  891. op.OplogReplay(*fo.OplogReplay)
  892. }
  893. if fo.Projection != nil {
  894. proj, err := transformBsoncoreDocument(coll.registry, fo.Projection)
  895. if err != nil {
  896. closeImplicitSession(sess)
  897. return nil, err
  898. }
  899. op.Projection(proj)
  900. }
  901. if fo.ReturnKey != nil {
  902. op.ReturnKey(*fo.ReturnKey)
  903. }
  904. if fo.ShowRecordID != nil {
  905. op.ShowRecordID(*fo.ShowRecordID)
  906. }
  907. if fo.Skip != nil {
  908. op.Skip(*fo.Skip)
  909. }
  910. if fo.Snapshot != nil {
  911. op.Snapshot(*fo.Snapshot)
  912. }
  913. if fo.Sort != nil {
  914. sort, err := transformBsoncoreDocument(coll.registry, fo.Sort)
  915. if err != nil {
  916. closeImplicitSession(sess)
  917. return nil, err
  918. }
  919. op.Sort(sort)
  920. }
  921. retry := driver.RetryNone
  922. if coll.client.retryReads {
  923. retry = driver.RetryOncePerCommand
  924. }
  925. op = op.Retry(retry)
  926. if err = op.Execute(ctx); err != nil {
  927. closeImplicitSession(sess)
  928. return nil, replaceErrors(err)
  929. }
  930. bc, err := op.Result(cursorOpts)
  931. if err != nil {
  932. closeImplicitSession(sess)
  933. return nil, replaceErrors(err)
  934. }
  935. return newCursorWithSession(bc, coll.registry, sess)
  936. }
  937. // FindOne returns up to one document that matches the model.
  938. func (coll *Collection) FindOne(ctx context.Context, filter interface{},
  939. opts ...*options.FindOneOptions) *SingleResult {
  940. if ctx == nil {
  941. ctx = context.Background()
  942. }
  943. findOpts := make([]*options.FindOptions, len(opts))
  944. for i, opt := range opts {
  945. findOpts[i] = &options.FindOptions{
  946. AllowPartialResults: opt.AllowPartialResults,
  947. BatchSize: opt.BatchSize,
  948. Collation: opt.Collation,
  949. Comment: opt.Comment,
  950. CursorType: opt.CursorType,
  951. Hint: opt.Hint,
  952. Max: opt.Max,
  953. MaxAwaitTime: opt.MaxAwaitTime,
  954. Min: opt.Min,
  955. NoCursorTimeout: opt.NoCursorTimeout,
  956. OplogReplay: opt.OplogReplay,
  957. Projection: opt.Projection,
  958. ReturnKey: opt.ReturnKey,
  959. ShowRecordID: opt.ShowRecordID,
  960. Skip: opt.Skip,
  961. Snapshot: opt.Snapshot,
  962. Sort: opt.Sort,
  963. }
  964. }
  965. // Unconditionally send a limit to make sure only one document is returned and the cursor is not kept open
  966. // by the server.
  967. findOpts = append(findOpts, options.Find().SetLimit(-1))
  968. cursor, err := coll.Find(ctx, filter, findOpts...)
  969. return &SingleResult{cur: cursor, reg: coll.registry, err: replaceErrors(err)}
  970. }
  971. func (coll *Collection) findAndModify(ctx context.Context, op *operation.FindAndModify) *SingleResult {
  972. if ctx == nil {
  973. ctx = context.Background()
  974. }
  975. sess := sessionFromContext(ctx)
  976. var err error
  977. if sess == nil && coll.client.topology.SessionPool != nil {
  978. sess, err = session.NewClientSession(coll.client.topology.SessionPool, coll.client.id, session.Implicit)
  979. if err != nil {
  980. return &SingleResult{err: err}
  981. }
  982. defer sess.EndSession()
  983. }
  984. err = coll.client.validSession(sess)
  985. if err != nil {
  986. return &SingleResult{err: err}
  987. }
  988. wc := coll.writeConcern
  989. if sess.TransactionRunning() {
  990. wc = nil
  991. }
  992. if !writeconcern.AckWrite(wc) {
  993. sess = nil
  994. }
  995. selector := makePinnedSelector(sess, coll.writeSelector)
  996. retry := driver.RetryNone
  997. if coll.client.retryWrites {
  998. retry = driver.RetryOnce
  999. }
  1000. op = op.Session(sess).
  1001. WriteConcern(wc).
  1002. CommandMonitor(coll.client.monitor).
  1003. ServerSelector(selector).
  1004. ClusterClock(coll.client.clock).
  1005. Database(coll.db.name).
  1006. Collection(coll.name).
  1007. Deployment(coll.client.topology).
  1008. Retry(retry)
  1009. _, err = processWriteError(op.Execute(ctx))
  1010. if err != nil {
  1011. return &SingleResult{err: err}
  1012. }
  1013. return &SingleResult{rdr: bson.Raw(op.Result().Value), reg: coll.registry}
  1014. }
  1015. // FindOneAndDelete find a single document and deletes it, returning the
  1016. // original in result.
  1017. func (coll *Collection) FindOneAndDelete(ctx context.Context, filter interface{},
  1018. opts ...*options.FindOneAndDeleteOptions) *SingleResult {
  1019. f, err := transformBsoncoreDocument(coll.registry, filter)
  1020. if err != nil {
  1021. return &SingleResult{err: err}
  1022. }
  1023. fod := options.MergeFindOneAndDeleteOptions(opts...)
  1024. op := operation.NewFindAndModify(f).Remove(true)
  1025. if fod.Collation != nil {
  1026. op = op.Collation(bsoncore.Document(fod.Collation.ToDocument()))
  1027. }
  1028. if fod.MaxTime != nil {
  1029. op = op.MaxTimeMS(int64(*fod.MaxTime / time.Millisecond))
  1030. }
  1031. if fod.Projection != nil {
  1032. proj, err := transformBsoncoreDocument(coll.registry, fod.Projection)
  1033. if err != nil {
  1034. return &SingleResult{err: err}
  1035. }
  1036. op = op.Fields(proj)
  1037. }
  1038. if fod.Sort != nil {
  1039. sort, err := transformBsoncoreDocument(coll.registry, fod.Sort)
  1040. if err != nil {
  1041. return &SingleResult{err: err}
  1042. }
  1043. op = op.Sort(sort)
  1044. }
  1045. return coll.findAndModify(ctx, op)
  1046. }
  1047. // FindOneAndReplace finds a single document and replaces it, returning either
  1048. // the original or the replaced document.
  1049. func (coll *Collection) FindOneAndReplace(ctx context.Context, filter interface{},
  1050. replacement interface{}, opts ...*options.FindOneAndReplaceOptions) *SingleResult {
  1051. f, err := transformBsoncoreDocument(coll.registry, filter)
  1052. if err != nil {
  1053. return &SingleResult{err: err}
  1054. }
  1055. r, err := transformBsoncoreDocument(coll.registry, replacement)
  1056. if err != nil {
  1057. return &SingleResult{err: err}
  1058. }
  1059. if firstElem, err := r.IndexErr(0); err == nil && strings.HasPrefix(firstElem.Key(), "$") {
  1060. return &SingleResult{err: errors.New("replacement document cannot contain keys beginning with '$'")}
  1061. }
  1062. fo := options.MergeFindOneAndReplaceOptions(opts...)
  1063. op := operation.NewFindAndModify(f).Update(bsoncore.Value{Type: bsontype.EmbeddedDocument, Data: r})
  1064. if fo.BypassDocumentValidation != nil && *fo.BypassDocumentValidation {
  1065. op = op.BypassDocumentValidation(*fo.BypassDocumentValidation)
  1066. }
  1067. if fo.Collation != nil {
  1068. op = op.Collation(bsoncore.Document(fo.Collation.ToDocument()))
  1069. }
  1070. if fo.MaxTime != nil {
  1071. op = op.MaxTimeMS(int64(*fo.MaxTime / time.Millisecond))
  1072. }
  1073. if fo.Projection != nil {
  1074. proj, err := transformBsoncoreDocument(coll.registry, fo.Projection)
  1075. if err != nil {
  1076. return &SingleResult{err: err}
  1077. }
  1078. op = op.Fields(proj)
  1079. }
  1080. if fo.ReturnDocument != nil {
  1081. op = op.NewDocument(*fo.ReturnDocument == options.After)
  1082. }
  1083. if fo.Sort != nil {
  1084. sort, err := transformBsoncoreDocument(coll.registry, fo.Sort)
  1085. if err != nil {
  1086. return &SingleResult{err: err}
  1087. }
  1088. op = op.Sort(sort)
  1089. }
  1090. if fo.Upsert != nil {
  1091. op = op.Upsert(*fo.Upsert)
  1092. }
  1093. return coll.findAndModify(ctx, op)
  1094. }
  1095. // FindOneAndUpdate finds a single document and updates it, returning either
  1096. // the original or the updated.
  1097. func (coll *Collection) FindOneAndUpdate(ctx context.Context, filter interface{},
  1098. update interface{}, opts ...*options.FindOneAndUpdateOptions) *SingleResult {
  1099. if ctx == nil {
  1100. ctx = context.Background()
  1101. }
  1102. f, err := transformBsoncoreDocument(coll.registry, filter)
  1103. if err != nil {
  1104. return &SingleResult{err: err}
  1105. }
  1106. fo := options.MergeFindOneAndUpdateOptions(opts...)
  1107. op := operation.NewFindAndModify(f)
  1108. u, err := transformUpdateValue(coll.registry, update, true)
  1109. if err != nil {
  1110. return &SingleResult{err: err}
  1111. }
  1112. op = op.Update(u)
  1113. if fo.ArrayFilters != nil {
  1114. filtersDoc, err := fo.ArrayFilters.ToArrayDocument()
  1115. if err != nil {
  1116. return &SingleResult{err: err}
  1117. }
  1118. op = op.ArrayFilters(bsoncore.Document(filtersDoc))
  1119. }
  1120. if fo.BypassDocumentValidation != nil && *fo.BypassDocumentValidation {
  1121. op = op.BypassDocumentValidation(*fo.BypassDocumentValidation)
  1122. }
  1123. if fo.Collation != nil {
  1124. op = op.Collation(bsoncore.Document(fo.Collation.ToDocument()))
  1125. }
  1126. if fo.MaxTime != nil {
  1127. op = op.MaxTimeMS(int64(*fo.MaxTime / time.Millisecond))
  1128. }
  1129. if fo.Projection != nil {
  1130. proj, err := transformBsoncoreDocument(coll.registry, fo.Projection)
  1131. if err != nil {
  1132. return &SingleResult{err: err}
  1133. }
  1134. op = op.Fields(proj)
  1135. }
  1136. if fo.ReturnDocument != nil {
  1137. op = op.NewDocument(*fo.ReturnDocument == options.After)
  1138. }
  1139. if fo.Sort != nil {
  1140. sort, err := transformBsoncoreDocument(coll.registry, fo.Sort)
  1141. if err != nil {
  1142. return &SingleResult{err: err}
  1143. }
  1144. op = op.Sort(sort)
  1145. }
  1146. if fo.Upsert != nil {
  1147. op = op.Upsert(*fo.Upsert)
  1148. }
  1149. return coll.findAndModify(ctx, op)
  1150. }
  1151. // Watch returns a change stream cursor used to receive notifications of changes to the collection.
  1152. //
  1153. // This method is preferred to running a raw aggregation with a $changeStream stage because it
  1154. // supports resumability in the case of some errors. The collection must have read concern majority or no read concern
  1155. // for a change stream to be created successfully.
  1156. func (coll *Collection) Watch(ctx context.Context, pipeline interface{},
  1157. opts ...*options.ChangeStreamOptions) (*ChangeStream, error) {
  1158. csConfig := changeStreamConfig{
  1159. readConcern: coll.readConcern,
  1160. readPreference: coll.readPreference,
  1161. client: coll.client,
  1162. registry: coll.registry,
  1163. streamType: CollectionStream,
  1164. collectionName: coll.Name(),
  1165. databaseName: coll.db.Name(),
  1166. }
  1167. return newChangeStream(ctx, csConfig, pipeline, opts...)
  1168. }
  1169. // Indexes returns the index view for this collection.
  1170. func (coll *Collection) Indexes() IndexView {
  1171. return IndexView{coll: coll}
  1172. }
  1173. // Drop drops this collection from database.
  1174. func (coll *Collection) Drop(ctx context.Context) error {
  1175. if ctx == nil {
  1176. ctx = context.Background()
  1177. }
  1178. sess := sessionFromContext(ctx)
  1179. if sess == nil && coll.client.topology.SessionPool != nil {
  1180. var err error
  1181. sess, err = session.NewClientSession(coll.client.topology.SessionPool, coll.client.id, session.Implicit)
  1182. if err != nil {
  1183. return err
  1184. }
  1185. defer sess.EndSession()
  1186. }
  1187. err := coll.client.validSession(sess)
  1188. if err != nil {
  1189. return err
  1190. }
  1191. wc := coll.writeConcern
  1192. if sess.TransactionRunning() {
  1193. wc = nil
  1194. }
  1195. if !writeconcern.AckWrite(wc) {
  1196. sess = nil
  1197. }
  1198. selector := makePinnedSelector(sess, coll.writeSelector)
  1199. op := operation.NewDropCollection().
  1200. Session(sess).WriteConcern(wc).CommandMonitor(coll.client.monitor).
  1201. ServerSelector(selector).ClusterClock(coll.client.clock).
  1202. Database(coll.db.name).Collection(coll.name).
  1203. Deployment(coll.client.topology)
  1204. err = op.Execute(ctx)
  1205. // ignore namespace not found erorrs
  1206. driverErr, ok := err.(driver.Error)
  1207. if !ok || (ok && !driverErr.NamespaceNotFound()) {
  1208. return replaceErrors(err)
  1209. }
  1210. return nil
  1211. }
  1212. // makePinnedSelector makes a selector for a pinned session with a pinned server. Will attempt to do server selection on
  1213. // the pinned server but if that fails it will go through a list of default selectors
  1214. func makePinnedSelector(sess *session.Client, defaultSelector description.ServerSelector) description.ServerSelectorFunc {
  1215. return func(t description.Topology, svrs []description.Server) ([]description.Server, error) {
  1216. if sess != nil && sess.PinnedServer != nil {
  1217. return sess.PinnedServer.SelectServer(t, svrs)
  1218. }
  1219. return defaultSelector.SelectServer(t, svrs)
  1220. }
  1221. }