Sreenath
Sreenath

Reputation: 510

How to convert string to BSON

I want to convert a string to BSON Obj to perform mongodb aggregate operation. All the queries will be stored in somewhere and now we have to convert string to BSON operation and show the result.

Lets say

var str = `[{"$match":{"tenantId":"TenantOne"}},{"$group":{"_id":{"referralType":"$referralType"},"value":{"$sum":1}}}]`

I've to convert to

var bsonobj = bson.A{
  bson.D{{
    Key: "$match", Value : bson.D{{
      Key : "tenantId" : Value: "TenantOne"
    }}
  }},
  bson.D{{
    Key: "$group", Value : bson.D{{
      Key : "_id" : Value: bson.D{{
        Key : "referralType" : Value: "$referralType"
      }},
      Key : "value" : Value: bson.D{{
        Key : "$sum" : Value: 1
      }}

    }}
  }}
}

I've tried Golang MongoDB-Driver - Bson Unmarshal! I'm not able to use it properly.

Upvotes: 1

Views: 1779

Answers (1)

Jay Jayswal
Jay Jayswal

Reputation: 116

try this:

    var str = `[{"$match":{"tenantId":"TenantOne"}},{"$group":{"_id":{"referralType":"$referralType"},"value":{"$sum":1}}}]`
fmt.Println(str)
var bdoc interface{}
err := bson.UnmarshalExtJSON([]byte(str),true,&bdoc)
fmt.Println(bdoc)
fmt.Println(err)

Upvotes: 2

Related Questions