MongoDB(Mgo v2)投影返回父结构

时间:2015-11-25 14:41:53

标签: mongodb go projection mgo database

我这里有一个建筑物对象,里面有一个地板物体数组。

在投影时,我的目标是在相应地匹配元素之后返回或计算建筑物对象内的楼层对象的数量。代码如下:

物件:

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 个答案:

答案 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)