亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

MongoDB (Mgo v2) 投影返回父結構

MongoDB (Mgo v2) 投影返回父結構

Go
慕神8447489 2021-11-22 19:26:50
我這里有一個建筑對象,里面有一個地板對象數組。投影時,我的目標是在相應地匹配元素后返回或計算建筑對象內的地板對象的數量。代碼如下:對象: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")}事實證明,無論我如何嘗試,查詢都會返回建筑對象,而不是樓層對象?為了讓查詢獲取和計算樓層而不是建筑物,我需要進行哪些更改?這樣做是為了在插入之前檢查建筑物內的樓層是否已經存在。如果有更好的方法,那么我會用更好的方法替換我的方法!
查看完整描述

1 回答

?
蝴蝶刀刀

TA貢獻1801條經驗 獲得超8個贊

您正在查詢一個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)


查看完整回答
反對 回復 2021-11-22
  • 1 回答
  • 0 關注
  • 241 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號