我在這裏有一個建築物對象,裏面坐着一個地板對象數組。MongoDB(Mgo v2)投影返回父結構
當投影時,我的目標是在相應地匹配元素之後返回或計算建築物對象內的樓層對象的數量。代碼如下:
對象:
type Floor struct {
// Binary JSON Identity
ID bson.ObjectId `bson:"_id,omitempty"`
// App-level Identity
FloorUUID string `bson:"f"`
// Floor Info
FloorNumber int `bson:"l"`
// Units
FloorUnits []string `bson:"u"`
// Statistics
Created time.Time `bson:"y"`
}
type Building struct {
// Binary JSON Identity
ID bson.ObjectId `bson:"_id,omitempty"`
// App-level Identity
BldgUUID string `bson:"b"`
// Address Info
BldgNumber string `bson:"i"` // Street Number
BldgStreet string `bson:"s"` // Street
BldgCity string `bson:"c"` // City
BldgState string `bson:"t"` // State
BldgCountry string `bson:"x"` // Country
// Building Info
BldgName string `bson:"w"`
BldgOwner string `bson:"o"`
BldgMaxTenant int `bson:"m"`
BldgNumTenant int `bson:"n"`
// Floors
BldgFloors []Floor `bson:"p"`
// Statistics
Created time.Time `bson:"z"`
}
代碼:
func InsertFloor(database *mgo.Database, bldg_uuid string, fnum int) error {
fmt.Println(bldg_uuid)
fmt.Println(fnum) // Floor Number
var result Floor // result := Floor{}
database.C("buildings").Find(bson.M{"b": bldg_uuid}).Select(
bson.M{"p": bson.M{"$elemMatch": bson.M{"l": fnum}}}).One(&result)
fmt.Printf("AHA %s", result)
return errors.New("x")
}
事實證明,不管我如何努力查詢返回大廈對象,而不是地板對象?爲了使查詢獲取並計算樓層而不是建築物,我需要進行哪些更改?
這樣做是爲了在插入之前檢查建築物內的樓層是否已經存在。如果有更好的方法,那麼我會更好地替換我的!
謝謝!
難道我的回答解決這個問題?如果是這樣,請接受是一個正確的答案。 – Pio
我用了一條與你所使用的管道不同且速度更快的管道。 –