Arjun Ajith
Arjun Ajith

Reputation: 1920

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

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

Upvotes: 3

Views: 1014

Answers (1)

Alex
Alex

Reputation: 21766

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)

Upvotes: 2

Related Questions