Upsert a document with shard key

35 views
Skip to first unread message

João Paulo Farias

unread,
Feb 25, 2015, 2:42:13 PM2/25/15
to mgo-...@googlegroups.com
Hi!

I am trying to use mgo with a sharded mongo cluster. The struct I am using has the shard key in it, so when I try to do something like:

type MyStruct struct {
 
ListingKey string
 
// other fields...
}
var x MyStruct{
 
"123",
 
// other fields
}
info
, err := session.DB("mydb").C("mycollection").Upsert(bson.M{"listingkey": "123"}, x)


This gives me an error:

Can't modify shard key's value. field: listingkey: "123" collection: mydb.mycollection

How do I go around this?

Thanks,

-- JP

Gustavo Niemeyer

unread,
Feb 25, 2015, 3:04:08 PM2/25/15
to mgo-...@googlegroups.com
Hi João,

This question and other related ones are answered in the following FAQ:

http://docs.mongodb.org/manual/faq/sharding/

Please let us know if there's anything else we can help with.
> --
> You received this message because you are subscribed to the Google Groups
> "mgo-users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to mgo-users+...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.



--

gustavo @ http://niemeyer.net

João Paulo Farias

unread,
Feb 25, 2015, 3:44:30 PM2/25/15
to mgo-...@googlegroups.com
I know how the update works, my question is how can I tell mgo to not include that field in the update part...

Because I am using a struct and not building a bson.M{} everytime I want to do an upsert it always includes all fields in the struct from what I can tell.

Is the solution to this to manually build the bson.M{} without that field?

Thanks,

--
JP

Gustavo Niemeyer

unread,
Feb 25, 2015, 3:47:58 PM2/25/15
to mgo-...@googlegroups.com
So you just want to avoid marshaling the struct field?

You can do that using a field tag:

type T struct {
Field string `bson:"-"`
}



On Wed, Feb 25, 2015 at 5:44 PM, João Paulo Farias

João Paulo Farias

unread,
Feb 25, 2015, 3:58:59 PM2/25/15
to mgo-...@googlegroups.com
Well I still want it to get the field from mongo when it loads, it just doesn't need to send it on the updates. This would completely ignore the field both ways...

Gustavo Niemeyer

unread,
Feb 25, 2015, 4:01:03 PM2/25/15
to mgo-...@googlegroups.com
You may also use the omitempty tag, so it will be omitted only if not provided:

Field string `bson:",omitempty"`

On Wed, Feb 25, 2015 at 5:58 PM, João Paulo Farias

João Paulo Farias

unread,
Feb 25, 2015, 4:06:11 PM2/25/15
to mgo-...@googlegroups.com
Perfect! That worked as expected.

Thanks Gustavo,

--
JP
Reply all
Reply to author
Forward
0 new messages