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

mongodb sorted order insertion using Mongoose in nodejs

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

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 检查时,属性信息正在存储,因为它在架构中给出,但我希望属性存储在 mongodb 中,如下所示

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

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

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