1// Copyright (C) MongoDB, Inc. 2014-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 7package bsonutil 8 9import ( 10 "bytes" 11 "fmt" 12 13 "github.com/mongodb/mongo-tools-common/json" 14 "github.com/mongodb/mongo-tools-common/util" 15 "go.mongodb.org/mongo-driver/bson" 16) 17 18// MarshalD is a wrapper for bson.D that allows unmarshalling 19// of bson.D with preserved order. Necessary for printing 20// certain database commands. 21type MarshalD bson.D 22 23// MarshalJSON makes the MarshalD type usable by 24// the encoding/json package. 25func (md MarshalD) MarshalJSON() ([]byte, error) { 26 var buff bytes.Buffer 27 buff.WriteString("{") 28 for i, item := range md { 29 key, err := json.Marshal(item.Key) 30 if err != nil { 31 return nil, fmt.Errorf("cannot marshal key %v: %v", item.Key, err) 32 } 33 val, err := json.Marshal(item.Value) 34 if err != nil { 35 return nil, fmt.Errorf("cannot marshal value %v: %v", item.Value, err) 36 } 37 buff.Write(key) 38 buff.WriteString(":") 39 buff.Write(val) 40 if i != len(md)-1 { 41 buff.WriteString(",") 42 } 43 } 44 buff.WriteString("}") 45 return buff.Bytes(), nil 46} 47 48// MakeSortString takes a bson.D object and converts it to a slice of strings 49// that can be used as the input args to mgo's .Sort(...) function. 50// For example: 51// {a:1, b:-1} -> ["+a", "-b"] 52func MakeSortString(sortObj bson.D) ([]string, error) { 53 sortStrs := make([]string, 0, len(sortObj)) 54 for _, docElem := range sortObj { 55 valueAsNumber, err := util.ToFloat64(docElem.Value) 56 if err != nil { 57 return nil, err 58 } 59 prefix := "+" 60 if valueAsNumber < 0 { 61 prefix = "-" 62 } 63 sortStrs = append(sortStrs, fmt.Sprintf("%v%v", prefix, docElem.Key)) 64 } 65 return sortStrs, nil 66} 67