【发布时间】:2017-04-25 12:29:52
【问题描述】:
在聚合项目中从索引 x 到 y 的数组元素,其中 x 在集合内部定义,y 是与匹配的数组元素的索引对应的数组元素。请看下面的例子,这样就更容易理解我想说的了。
优惠券收藏
{"coupon_id": "coupon01", "codes": ["FLAT30", "FLAT50", "FLAT70", "FLAT90"], "curr_index": 0}
例如,请参见下面的示例代码,我正在尝试获取从 curr_index 到 (curr_index + n) 的优惠券代码,其中 n 是 coupon_ctrs 中对应于 coupons_ids 示例索引的数字 - 对于 id "584559bd1f65d363bd5d25fd" n 是 1,对于 id "58455a5c1f65d363bd5d2600" n 是 2,对于 id "584878eb0005202c64b0cc5d" n 是 3。
coupons_ctrs = [1, 2, 3];
coupons_ids = ["584559bd1f65d363bd5d25fd", "58455a5c1f65d363bd5d2600", "584878eb0005202c64b0cc5d"];
int n = 2;
couponmodel.aggregate(
{ $match : { '_id': { $in : coupons_ids }} },
{ $project: {_id:0, codes : /* How to use slice here so that codes array will be returned between cur_index and (curr_index + coupons_ctr corresponding to the index coupon id is found, example- for _id "584559bd1f65d363bd5d25fd" it should be 1 and so on) */} },
function(err, docs) {
if (err) {
} else {
}
});
更新
正如 Styvane 建议的那样,我可以使用 $zip,它会完美运行,但由于我使用的是 mongoDB 3.2.11,所以我不能使用它,那么在 mongodb 3.2 中使用 $zip 功能的解决方案是什么。 11 ??
谁能告诉我如何包含这个 coupon_ctrs 数组并在聚合管道中使用它。
【问题讨论】:
标签: mongodb mongoose aggregation-framework