Last active
August 11, 2016 18:19
-
-
Save cezarsa/1a244965ae085c919336c58815172e49 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "gopkg.in/mgo.v2" | |
| "gopkg.in/mgo.v2/bson" | |
| ) | |
| func withUpsert(c *mgo.Collection) { | |
| _, err := c.Upsert(bson.M{"_id": 1, "x": 2}, bson.M{"$set": bson.M{"x": 3}}) | |
| fmt.Printf("ISDUP: %v - %s\n", mgo.IsDup(err), err) | |
| // OUTPUT - ISDUP: true - E11000 duplicate key error index: test-mgo-dup.a.$_id_ dup key: { : 1 } | |
| } | |
| func withApply(c *mgo.Collection) { | |
| _, err := c.Find(bson.M{"_id": 1, "x": 2}).Apply(mgo.Change{ | |
| Update: bson.M{"$set": bson.M{"x": 3}}, | |
| Upsert: true, | |
| }, nil) | |
| fmt.Printf("ISDUP: %v - %s\n", mgo.IsDup(err), err) | |
| // OUTPUT - ISDUP: false - not found | |
| } | |
| func main() { | |
| conn, err := mgo.Dial("127.0.0.1:27017") | |
| if err != nil { | |
| panic(err) | |
| } | |
| c := conn.DB("test-mgo-dup").C("a") | |
| c.DropCollection() | |
| err = c.Insert(bson.M{"_id": 1, "x": 1}) | |
| if err != nil { | |
| panic(err) | |
| } | |
| withUpsert(c) | |
| withApply(c) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment