如何在Mongodb、Mgo中更新子文档数组字段以及其他字段?

huangapple go评论80阅读模式
英文:

How to update a sub-document array fields along with some other fields in Mongodb, Mgo?

问题

我们可以在Mgo中更新子文档数组字段以及其他文档字段吗?如果可以的话,请帮我解决我的查询问题。

c := db.C("user")
colQuerier := bson.M{"email": *olduname}
change := bson.M{"$set": bson.M{"password": *pwd, "place": *place, "emails.$.received": *received, "emails.$.sent": *sent}}
err := c.Update(colQuerier, change)

我的数据库结构如下:

type Emails struct {
    Id       bson.ObjectId `bson:"_id,omitempty"`
    Received string
    Sent     string
}

type User struct {
    Id       bson.ObjectId `bson:"_id,omitempty"`
    Email    string
    Password string
    Place    string
    Emails   []Emails
}

我得到了一个运行时错误,错误信息是:定位操作符在查询中找不到所需的匹配项。未展开的更新:emails.$.received

英文:

Can we update sub-document array fields along with other document fields in Mgo?
If so, please help me with my query.

 c := db.C("user")
 colQuerier := bson.M{"email": *olduname}
 change := bson.M{"$set":bson.M{"password":*pwd, "place":*place, "emails.$.received":*received,"emails.$.sent":*sent}}
    	err := c.Update(colQuerier, change)

My Database Structs are as follows:

type Emails struct{
	Id          bson.ObjectId `bson:"_id,omitempty"`
	Received string
	Sent	string	
}

type User   struct {
	Id          bson.ObjectId `bson:"_id,omitempty"`
	Email       string
	Password    string
	Place		string
	Emails     
		
}

I am getting a run time error saying: The positional operator did not find the match needed from the query. Unexpanded update: emails.$.received

答案1

得分: 2

应该将emails.received作为received不是一个数组,所以你不需要使用位置操作符$

c := db.C("user")
colQuerier := bson.M{"email": *olduname}
change := bson.M{"$set": bson.M{"password": *pwd, "place": *place, "emails.received": *received}}
err := c.Update(colQuerier, change)
英文:

It should be emails.received as received is not an array, so you don't need the positional operator $:

c := db.C("user")
colQuerier := bson.M{"email": *olduname}
change := bson.M{"$set":bson.M{"password":*pwd, "place":*place, "emails.received":*received}}
err := c.Update(colQuerier, change)

huangapple
  • 本文由 发表于 2016年2月4日 19:35:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/35199952.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定