【问题标题】:Mongoose query in array for retrieving elements starting from index 0 to n where n is the position of the element from the last数组中的猫鼬查询,用于检索从索引 0 到 n 开始的元素,其中 n 是从最后一个元素开始的位置
【发布时间】:2016-11-07 18:39:46
【问题描述】:

我想返回数组中出现在数组中特定位置之前的所有元素,例如,请参见下面的示例。

var arr = [59, 34, 6, 9, 45, 67, 89, 56, 34, 26, 56, 45] 现在位置 = 5,这意味着从最后一个位置开始的第 5 个位置,即 56 我想获得数组 [56, 89, 67, 45, 9, 6, 34, 59]

Mongoose 架构

var user_coupons_schema = new Schema({
mobile_no: {type: String, unique: true},
coupons: [{type: String}]
});

猫鼬查询

usercoupons.findOne({mobile_no: mobile_no}, {'_id':0, coupons: { "$slice": [-skip, limit]}}, function(err, docs) {

更新

使用聚合我的代码在下面给出,但有人可以告诉我为什么低于值在 $slice 中出现 NaN

"arr_size" - 跳过 -> NaN

usercoupons.aggregate(
        { $match : {mobile_no: mobile_no} },
        { $project: {arr_size: {$size: "$coupons"}} },
        { $project: {_id:0, coupons: { "$slice": [0, "arr_size" - skip]}} },
        function(err, docs) {
            if (err) {
                console.log('Hii1');
            } else {
                if (docs) {
                    console.log('Hii2');
                } else {
                    console.log('Hii3');
                }
            }
        }
    );

【问题讨论】:

  • 能否提供有关架构的更多信息并展示您的尝试?
  • 我想使用 slice,但是在 slice[skip, limit] 中,有两个参数可以跳过我可以使用 -position 但我不知道应该使用什么限制??

标签: arrays node.js mongodb mongoose


【解决方案1】:

我假设你只是有一个基于你的评论的 JavaScript 数组。

var arr = [59, 34, 6, 9, 45, 67, 89, 56, 34, 26, 56, 45];
var ind = 5;
var subset = arr.slice(0, arr.length - ind + 1); // if you want to include value at ind'th position from the last
// OR    
var subset = arr.slice(0, arr.length - ind); // if you don't want to include value at ind'th position from the last

【讨论】:

  • 我没有简单的 javascript 数组,我的意思是我有一个包含简单数组的架构,请查看我编辑的帖子。
  • @PrakashKumar,你可以得到doc,然后按照我上面显示的方式处理数组。另一种选择是在返回文档之前使用 MongoDB aggregate() 方法获取数组的 sizeslice 它。
  • 我只想要 0 到 n 之间的元素这就是为什么我不想使用第一个选项,你能写聚合查询方法吗??
  • 你在吗??你能告诉我聚合查询代码吗?
  • 你能告诉我聚合查询代码是什么吗??
猜你喜欢
  • 1970-01-01
  • 2017-06-09
  • 1970-01-01
  • 2012-04-30
  • 2018-05-10
  • 2011-03-28
  • 1970-01-01
  • 2014-06-27
  • 1970-01-01
相关资源
最近更新 更多