这是我喜欢使用的:
func dbInsert(collection string, insert bson.M, session *mgo.Session) error {
c := session.DB(your_DB).C(collection)
err := c.Insert(insert)
return err
}
func dbUpsert(collection string, selector bson.M, update bson.M, session *mgo.Session) (*mgo.ChangeInfo, error) {
c := session.DB(your_DB).C(collection)
info, err := c.Upsert(selector, update)
return info, err
}
func dbFindOne(collection string, findBson bson.M, selectBson bson.M, session *mgo.Session) (map[string]interface{}, error) {
c := session.DB(your_DB).C(collection)
getMap := make(map[string]interface{})
err := c.Find(findBson).Select(selectBson).One(&getMap)
return getMap, err
}
func dbFindAll(collection string, findBson bson.M, selectBson bson.M, session *mgo.Session) (map[string]interface{}, error) {
c := session.DB(your_DB).C(collection)
getMap := make(map[string]interface{})
err := c.Find(findBson).Select(selectBson).All(&getMap)
return getMap, err
}
func dbUpdate(collection string, selector bson.M, update bson.M, session *mgo.Session) error {
c := session.DB(your_DB).C(collection)
setBson := bson.M{};
setBson["$set"] = update;
//
updateError := c.Update(selector, setBson)
//
return updateError
}
func dbRemoveOne(collection string, selector bson.M, session *mgo.Session) error {
c := session.DB(your_DB).C(collection)
removeError := c.Remove(selector)
return removeError
}
func dbRemoveAll(collection string, selector bson.M, session *mgo.Session) (*mgo.ChangeInfo, error) {
c := session.DB(your_DB).C(collection)
removeInfo, removeError := c.RemoveAll(selector)
return removeInfo, removeError
}
下面是 find 的示例查询:
//FIND ONE:
employeeInfo, err := dbFindOne("employees", bson.M{"name": "john"}, bson.M{"salary": 1, "homeCity": 1}, mongo_session)
if err != nil {
fmt.Println("Error getting employee info: ", err)
}else{
//you can get the salary as an int:
salary := employeeInfo["salary"].(int)
//or get their homeCity as a string:
homeCity := employeeInfo["homeCity"].(string)
}
这例如在集合“employees”中查找名为“john”的员工的“salary”。
sn-p 中的所有方法的工作方式几乎与dbFindOne() 完全相同。
希望这会有所帮助!