Home > Article > Backend Development > How to remove additional keys added while inserting nested structure in mongodb
php editor Apple brings you an article on how to remove additional keys added when inserting nested structures in mongodb. When using mongodb to store data, sometimes we add some additional keys to the nested structure to facilitate query and operation. But how do we remove these additional keys when we no longer need them? This article will provide you a simple and effective method to help you easily remove the additional keys added when inserting nested structures in mongodb. Let’s take a look!
Assume this is my structure definition,
type partialContent struct { key string `json:"key" bson"key"` value string `json:"value" bson:"value"` } type content struct { id string `json:"id" bson:"_id,omitempty"` partialContent }
When content is stored in MongoDB, it is stored as
{ "_id": ObjectID, "partialcontent": { "key": "...", "value": "..." } }
But JSON unmarshalling returns
{ "_id": ObjectID, "key": "...", "value": "..." }
How to remove additional keys partialcontent in MongoDB?
First, you need to export the structure fields, otherwise the driver will skip them.
If you do not want to embed the document in MongoDB, use the ,inline
bson tag option:
type PartialContent struct { Key string `json:"key" bson"key"` Value string `json:"value" bson:"value"` } type Content struct { ID string `json:"id" bson:"_id,omitempty"` PartialContent `bson:",inline"` }
Insert the value:
v := Content{ ID: "abc", PartialContent: PartialContent{ Key: "k1", Value: "v1", }, }
This document will be generated in MongoDB:
{ "_id" : "abc", "key" : "k1", "value" : "v1" }
The above is the detailed content of How to remove additional keys added while inserting nested structure in mongodb. For more information, please follow other related articles on the PHP Chinese website!