Mongodb
安装
略
操作
- 启动后台服务程序
mongod # 如果是默认的数据路径需要root权限, 可以修改数据存储位置。
- 进入命令行
```
mongo
show databases # 列出数据库 use {database_name} # 切换db指针到某个数据库 show collections # 展示所有的collections (tables) db.{collection_name}.find() # 列出所有元素 .pretty() # 以格式化的json形式展示结果
db.{c_name}.insert({json}) # 插入 db.{c_name}.remove({‘title’: ‘what’}) # 删除指定条件元素 ```
Go 操作Mongodb + 抽象工厂模式设计
import "gopkg.in/mgo.v2"
/** Databaser is An abstract factory interface, if you want to add a new database backend, you must implement all function*/
type Databaser interface {
iUser
}
func GetDatabaseConncect(db string) (Databaser) {
if db == "mongodb" { return newMongodb()}
panic("db is not the validate database backend.")
return nil
}
// anonymous member, we can directly point the final function, such as AddUser.
type Mongodb struct{
MongodbUser
}
/** The models definition and corresponding interface. */
type User struct {
// user'name or oauth2 website username
Username string
// oauth2 authenticated website
Source string
}
type iUser interface {
AddUser(user User) (error)
DeleteUser(user User) (error)
SelectUser(pairs map[string]string) ([]User, error)
}
type MongodbUser struct {
database string
collection string `collection name`
}
// Mongodb's construction, also construct it's interface implementation struct, i.e. subclass.
func newMongodb() (*Mongodb){
var mdb = new(Mongodb)
// construct All databases name and collections name, need to be explicit.
mdb.MongodbUser.database = "Mongodb";
mdb.MongodbUser.collection = "Users"; // table name.
return mdb
}
func (self MongodbUser) AddUser(user User) (error) {
session, err := mgo.Dial(MONGO_DB_SEVER)
if err != nil {
return err
}
defer session.Close()
session.SetSafe(&mgo.Safe{})
c := session.DB(self.database).C(self.collection)
err = c.Insert(&user) // It can insert not only one Object, it acquires "...&interface"
if err != nil {
return err
}
return nil;
}
func (self MongodbUser) DeleteUser(user User) (error) {
return nil;
}
func (self MongodbUser) SelectUser(pairs map[string]string) ([]User, error) {
return nil, nil;
}