gpt4 book ai didi

json - 操纵mongodb的bson.D输出格式

转载 作者:行者123 更新时间:2023-12-02 11:26:32 24 4
gpt4 key购买 nike

我正在使用FindOne查询一行数据(单个文档):
包主

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
}
这只是结果显示方式的一小部分:
[
{
"Key": "_id",
"Value": "1600540844649"
},
{
"Key": "hostname",
"Value": "DESKTOP-xxxxxx"
},
{
"Key": "cmdLine",
"Value": []
},
{
"Key": "pid",
"Value": 4816
}
]
但这就是我想要的样子:
[
{
"_id": "1600540844649"
},
{
"hostname": "DESKTOP-xxxxxx"
},
{
"cmdLine": []
},
{
"pid": 4816
}
]
或者:
[
{
"_id": "1600540844649",
"hostname": "DESKTOP-xxxxxx",
"cmdLine": [],
"pid": 4816,
}
]
我该怎么办?我已经搜索了SO和Google,但没有运气。我应该使用 struct还是创建任何对象?我还搜索了将bson保存/转换为json的方法,但是有解决方案。

最佳答案

我自己找到了解决方案:
使用bson.M而不是bson.D解决了我的问题:

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
}

关于json - 操纵mongodb的bson.D输出格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64092732/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com