在带有id的对象数组中使用lookup

时间:2018-05-28 13:17:30

标签: mongodb go mgo

我在对象数组中使用查找时遇到问题。

我的结构是

type MerchantList struct {
    MerchantID       bson.ObjectId    `json:"merchantId,omitempty" bson:"merchantId,omitempty"`
    Merchant         *Merchant        `json:"merchant,omitempty" bson:"merchant,omitempty"`
    MerchantRevenue  float64          `json:"merchantRevenue" bson:"merchantRevenue"`
    MerchantFee      int              `json:"merchantFee,omitempty" bson:"merchantFee,omitempty"`
}

type Weeks struct {
    ID               bson.ObjectId    `json:"id,omitempty" bson:"_id,omitempty" description:"Object ID"`
    MerchantList     []*MerchantList  `json:"merchantList,omitempty" bson:"merchantList,omitempty"`
    CreatedAt        int64            `json:"createdAt" bson:"createdAt" description:"Created date."`
    UpdatedAt        int64            `json:"updatedAt" bson:"updatedAt" description:"Updated date."`
}

我的收藏品结构如下:

{
    "_id" : ObjectId("5af8bdb20b0aa02928514a00"),
    "name" : "Week 1",
    "merchantList" : [ 
        {
            "merchantId" : ObjectId("5ad79c500b0aa07ed040fe4b"),
            "merchantRevenue" : 126500.0,
            "merchantFee" : 25
        }
    ]
}

我的查询是

pipe := []bson.M{
    {"$unwind": bson.M{
        "path": "$merchant.merchantList",
        "preserveNullAndEmptyArrays": true}},
    {"$lookup": bson.M{
        "from":         "merchant",
        "localField":   "merchantList.merchantId",
        "foreignField": "_id",
        "as":           "merchant",
    }},
}

我希望退出程序就像那样

{
    "items": [
        {
            "id": "5af8bdb20b0aa02928514a00",
            "merchantList": [
                {
                    "merchantId": "5ad79c500b0aa07ed040fe4b",
                    "merchant": {
                        "name": "Merchant 1"
                    }
                }
            ],
        }
    ]
}

如果有人知道该怎么做。这将非常有帮助:))

0 个答案:

没有答案