简体   繁体   中英

mongodb sorted order insertion using Mongoose in nodejs

I have a mongoose schema shown below

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'});
  }

});

When I'm checking from mongodb attrib information is storing as it is given in schema, but I want attrib store in mongodb like below

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

I want atrrib information will store in descending order by Year and Month

MongoDB will not automatically sort the data for you.

If you want to store sorted data then you'll have to sort it manually before inserting it in Mongo. For that you can try this -

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;})
});

This sort method will sort your objects in descending order. This is just a naive implementation. Feel free to improve the method as you like.

And if you want to store unsorted data into Mongo and want it to be sorted by Mongo when you query the data then you'll have to use the sort() operator in your query. Read about it here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM