mongodb_store_kv.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package mongodb
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/filer"
  6. "github.com/chrislusf/seaweedfs/weed/glog"
  7. "go.mongodb.org/mongo-driver/bson"
  8. "go.mongodb.org/mongo-driver/mongo"
  9. "go.mongodb.org/mongo-driver/mongo/options"
  10. )
  11. func (store *MongodbStore) KvPut(ctx context.Context, key []byte, value []byte) (err error) {
  12. dir, name := genDirAndName(key)
  13. c := store.connect.Database(store.database).Collection(store.collectionName)
  14. opts := options.Update().SetUpsert(true)
  15. filter := bson.D{{"directory", dir}, {"name", name}}
  16. update := bson.D{{"$set", bson.D{{"meta", value}}}}
  17. _, err = c.UpdateOne(ctx, filter, update, opts)
  18. if err != nil {
  19. return fmt.Errorf("kv put: %v", err)
  20. }
  21. return nil
  22. }
  23. func (store *MongodbStore) KvGet(ctx context.Context, key []byte) (value []byte, err error) {
  24. dir, name := genDirAndName(key)
  25. var data Model
  26. var where = bson.M{"directory": dir, "name": name}
  27. err = store.connect.Database(store.database).Collection(store.collectionName).FindOne(ctx, where).Decode(&data)
  28. if err != mongo.ErrNoDocuments && err != nil {
  29. glog.Errorf("kv get: %v", err)
  30. return nil, filer.ErrKvNotFound
  31. }
  32. if len(data.Meta) == 0 {
  33. return nil, filer.ErrKvNotFound
  34. }
  35. return data.Meta, nil
  36. }
  37. func (store *MongodbStore) KvDelete(ctx context.Context, key []byte) (err error) {
  38. dir, name := genDirAndName(key)
  39. where := bson.M{"directory": dir, "name": name}
  40. _, err = store.connect.Database(store.database).Collection(store.collectionName).DeleteOne(ctx, where)
  41. if err != nil {
  42. return fmt.Errorf("kv delete: %v", err)
  43. }
  44. return nil
  45. }
  46. func genDirAndName(key []byte) (dir string, name string) {
  47. for len(key) < 8 {
  48. key = append(key, 0)
  49. }
  50. dir = string(key[:8])
  51. name = string(key[8:])
  52. return
  53. }