为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 206 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信