如何正确编写嵌套的bson.M {}

Suppose we have the following struct:

type shop struct {
   ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
   Brands *brand         `json:"brand,omitempty" bson:"brand,omitempty"`
}

type brand struct {
  ID primitive.ObjectID `json:"_id,omitempty" bson:"deploymentid,omitempty"`
}

I tried to find a document using findOne() but I don't get any document even there is a result match by using the MongoDB shell.

filter := bson.M{"brand" : bson.M{"_id" : someValue}}
var shopWithBrand shop
mycollection.findOne(ctx , filter).Decode(&shopWithBrand)

What mistake did I make?

douzhiba6873
douzhiba6873 您的struct标记完全无效,甚至不会编译。
大约一年之前 回复

1个回答



此过滤器:</ p>

 过滤器:= bson.M {“ brand”:  bson.M {“ _ id”:someValue}} 
</ code> </ pre>

告诉您要包​​含 brand </ code>字段的文档是嵌入式文档< strong>具有单个 _id </ code>字段</ strong>,其值是 someValue </ code>的值。</ p>

如果您的 嵌入式文档仅包含一个 _id </ code>字段,但是您的嵌入式 brand </ code>会将此ID字段映射到 deploymentid </ code>,并且很可能具有其他字段,例如 很好(为了使示例最小化,已“删除”了),这就是为什么它不匹配的原因。</ p>

相反,您希望文档具有 brand </ code> 字段是具有匹配的 deployment </ code>字段以及其他字段</ em>的文档。 这是您可以这样表达的方式:</ p>

  filter:= bson.M {“ brand.deploymentid”:someValue} 
</ code> </ pre>
< / DIV>

展开原文

原文

This filter:

filter := bson.M{"brand" : bson.M{"_id" : someValue}}

Tells you want documents that have a brand field that is an embedded document having a single _id field whose value is the value of someValue.

This would actually work if your embedded documents would only consist of this single _id field, but your embedded brand has this ID field mapped to deploymentid and most likely has other fields as well (which you "stripped off" to minimize the example), and that is why it won't match.

Instead you want documents that have a brand field being a document that has a matching deployment field among other fields. This is how you can express that:

filter := bson.M{"brand.deploymentid" : someValue}

dongpang2483
dongpang2483 我以为我也不必指定其他字段的值,brand.deploymentid的工作谢谢:)
大约一年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐