2015-11-25 48 views
0

我在這裏有一個建築物對象,裏面坐着一個地板對象數組。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") 
} 

事實證明,不管我如何努力查詢返回大廈對象,而不是地板對象?爲了使查詢獲取並計算樓層而不是建築物,我需要進行哪些更改?

這樣做是爲了在插入之前檢查建築物內的樓層是否已經存在。如果有更好的方法,那麼我會更好地替換我的!

謝謝!

+0

難道我的回答解決這個問題?如果是這樣,請接受是一個正確的答案。 – Pio

+0

我用了一條與你所使用的管道不同且速度更快的管道。 –

回答

1

您正在查詢Building文檔,因此mongo會將此內容返回給您,即使您嘗試使用投影來屏蔽其某些字段。

我不知道的方式來計算一個mongo數組元素的find查詢號碼,但你可以使用聚合框架,在那裏你有$size運營商所做的正是這一點。所以,你應該發出這樣的查詢到mongo

db.buildings.aggregate([ 
{ 
    "$match": 
    { 
     "_id": buildingID, 
     "p": { 
      "$elemMatch": {"l": fNum} 
     } 
    } 
}, 
{ 
    "$project": 
    { 
     nrOfFloors: { 
      "$size": "$p" 
     } 
    } 
}]) 

將目光中go

result := []bson.M{} 
match := bson.M{"$match": bson.M{"b": bldg_uuid, "p": bson.M{"$elemMatch": bson.M{"l": fNum}}}} 
count := bson.M{"$project": bson.M{"nrOfFloors": bson.M{"$size": "$p"}}} 
operations := []bson.M{match, count} 
pipe := sess.DB("mgodb").C("building").Pipe(operations) 
pipe.All(&result) 
+0

但我覺得地板已經在建築物內的一個數組裏面了?你讀過的代碼?唯一的ID就是爲了讓事情變得方便。它與mongo的NoSQL理念無關。 –