mongodb在nodejs中使用Mongoose排序顺序插入

时间:2017-01-24 10:26:24

标签: node.js mongodb mongoose-schema

我有一个如下所示的猫鼬模式

var testdata = new Test({
        Product_Type: 10, 
        Product_ID: 'GPR',
        attrib: [   
                    {
                        Year:2017,
                        Month: 3
                    },
                    {
                       Year:2011,
                       Month: 3
                    },
                    {
                        Year:2012,
                        Month: 3
                    },
                    {
                        Year:2015,
                        Month: 3
                    }
                ],
    });

testdata.save(function(err, testdata) {
  if(err){
      console.log('saving data error',err);
  }else{
       res.status(200).json({'msg':'Data inserted'});
  }

});

当我从mongodb检查attrib信息是存储在架构中给出,但我想在mongodb中的attrib商店如下

   {
        Year:2017,
        Month: 3
    },
    {
        Year:2015,
        Month: 3
    },
    {
        Year:2012,
        Month: 3
    },
    {
       Year:2011,
       Month: 3
    }

我希望atrrib信息按年和月按降序存储

1 个答案:

答案 0 :(得分:0)

MongoDB不会自动为您排序数据。

如果您想存储已排序的数据,那么在将其插入Mongo之前,您必须手动对其进行排序。为此你可以尝试这个 -

var testdata = new Test({
    Product_Type: 10, 
    Product_ID: 'GPR',
    attrib: [   
                {
                    Year:2017,
                    Month: 3
                },
                {
                   Year:2011,
                   Month: 3
                },
                {
                    Year:2012,
                    Month: 3
                },
                {
                    Year:2015,
                    Month: 3
                }
            ].sort(function(d1,d2) {if(d1.Year==d2.Year) return d2.Month - d1.Month; else return d2.Year - d1.Year;})
});

此排序方法将按降序对对象进行排序。这只是一个天真的实现。随意改进方法。

如果您想将未分类的数据存储到Mongo中并希望在查询数据时由Mongo对其进行排序,那么您将不得不在查询中使用sort()运算符。阅读它here

相关问题