TL;DR:MongoDB 驱动程序是否提供了编组和解组文档单个字段的功能?
这是一个非常简单的问题,但这里有一些上下文:
我有一个工作人员负责在 2 个独立的数据库之间同步数据。当它接收到事件消息时,表明某些文档必须同步,它会在主数据库中选择文档,并将其复制到另一个数据库中(这是一个完全不同的数据库,而不是副本集)。
问题是:我不知道该文档的完整结构,因此为了保留数据,我必须在 mapmap[string]interface{}
或以bson.M
相同方式工作的 a 中解组该文档。但这似乎有很多开销,要解组我什至不使用的所有这些数据,只是将其编组回另一个数据库。
所以我考虑创建一个只存储该文档的二进制值的结构,而不执行任何编组或解组以减少开销,如下所示:
type Document = map[string]Field
type Field struct {
Type bsontype.Type
Value []byte
}
func (f Field) MarshalBSONValue() (bsontype.Type, []byte, error) {
return f.Type, f.Value, nil
}
func (f *Field) UnmarshalBSONValue(btype bsontype.Type, value []byte) error {
f.Type = btype
f.Value = value
return nil
}
使用这种结构,我确实可以减少要解析的数据量,但是现在,我需要手动解组本文档中我需要使用的一个值。
所以我想知道MongoDB驱动程序是否有一些功能,例如:
// Hypothetical function to get the value of a BSON
var status string
if err := decodeBSON(doc['status'].Type, doc['status'].Value, &status); err != nil {
return err
}
和
// Hypothetical function to set the value of a BSON
createdAt, err := encodeBSON(bsontype.Date, time.Now())
if err != nil {
return err
}
doc["createdAt"] = Field{Type: bsontype.Date, Value: createdAt}
我怎样才能做到这一点?