1

Im using FindOne to query one row of data (single document):

package main

import (
    "context"
    "fmt"
    "github.com/fatih/color" 
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

func mongoDbFindOne(key, value string) bson.D {
    var result bson.D
    _ = Collection.FindOne(context.TODO(), bson.D{{key, value}}).Decode(&result)
    color.Green("[+] Found: %+v\n", result)
    return result
}

And this a small part of how the result is shown:

[
    {
        "Key": "_id",
        "Value": "1600540844649"
    },
    {
        "Key": "hostname",
        "Value": "DESKTOP-xxxxxx"
    },
    {
        "Key": "cmdLine",
        "Value": []
    },
    {
        "Key": "pid",
        "Value": 4816
    }
]

But this how i want it to be:

[
    {
        "_id": "1600540844649"
    },
    {
        "hostname": "DESKTOP-xxxxxx"
    },
    {
        "cmdLine": []
    },
    {
        "pid": 4816
    }
]

Or:

[
    {
        "_id": "1600540844649",
        "hostname": "DESKTOP-xxxxxx",
        "cmdLine": [],
        "pid": 4816,
    }
]

What should i do? I have searched through SO and google but no luck. Should i use struct or creating any objects? I also searched for saving/converting bson to json but there is solution to it.

1 Answer 1

1

I found the solution myself: Using bson.M instead of bson.D solved my issue:

import (
    "context"
    "fmt"
    "github.com/fatih/color" 
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

func mongoDbFindOne(key, value string) bson.M {
    var result bson.M
    _ = Collection.FindOne(context.TODO(), bson.M{key:value}).Decode(&result)
    color.Green("[+] Found: %+v\n", result)
    return result
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.