【发布时间】:2018-07-26 20:23:21
【问题描述】:
我正在尝试使用 mongodb 进行左连接,以计算每个用户在每个商店中购买的每种产品的数量。我是聚合和 nosql 的新手,在查看如何将 users.products.stores 加入到 stores 表以获取商店名称和 products 表到 users.products.productId 以获取名称时遇到问题产品。
我想打印出以下json:
{"userId": "user1", "StoreName": "Store 1", "ProductName": "Crest Toothpaste", "# of Purchases": 200}
我使用的是 mongodb 3.6 版
- 商店
- 身份证
- 姓名
- 城市
- 状态
- 邮政编码
- 用户
- 身份证
- 用户ID
- 电子邮件地址
- 产品:[{ productId,商店:[{storeId}] }]
- 产品
- 身份证
- sku
- 价格
- productRewards:[{ pointsNeeded, rewardAmount }]
这是一个模式示例:
UserSchema: Schema = new Schema({
userName: {type: Schema.Types.String, minlength: 6, maxlength: 10, required: true},
emailAddress: {type: Schema.Types.String, minlength: 8, maxlength: 55, required: true}
products: [{productId: {type: Schema.Types.ObjectId, required: true, ref: 'product’},
stores: [{storeId: {type: Schema.Types.ObjectId, required: true, ref: ‘store’}]]
})
ProductSchema: Schema = new Schema({
name: {type: Schema.Types.String, minlength: 1, maxlength: 30, required: true},
price: {type: Schema.Types.Number, required: true},
productRewards: [{
pointsNeeded: {type: Schema.Types.Number, required: true},
rewardAmount: {type: Schema.Types.Number, required: true}
}]
}
StoreSchema: Schema = new Schema({
name: {type: Schema.Types.String, minlength: 10, maxlength: 30, required: true},
city: {type: Schema.Types.String, minlength: 1, maxlength: 35, required: true},
state: {type: Schema.Types.String, minlength: 1, maxlength: 35, required: true},
zipCode: {type: Schema.Types.String, minlength: 5, maxlength: 13, required: true},
}
我试图做这样的事情,但我并没有让它只拉出连接左侧和右侧的 memberId 字段相等的地方,而是它似乎更像是一个完整的连接:
db.user.aggregate(
{ $unwind : "$products" },
{ $unwind : "$products.stores" },
{ "$lookup": {
from: "stores",
localField: "storeId",
foreignField: "_id",
as: "stores"
}
})
考虑到一个是子文档,我如何执行必要的连接?我对每个连接的外观感到困惑,尤其是子子文档。
【问题讨论】:
标签: mongodb mongoose aggregation-framework