dongtan4046 2019-07-08 11:20
浏览 646

如何正确编写嵌套的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?

  • 写回答

1条回答

  • doubi12138 2019-07-08 11:25
    关注

    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}
    
    评论

报告相同问题?

悬赏问题

  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果