how to get the last N records in MongoDB

.sort()

db.foo.find().sort({x:1});

The 1 will sort ascending (oldest to newest) and -1 will sort descending (newest to oldest.)

If you use the auto created _id field it has a date embedded in it … so you can use that to order by …

db.foo.find().sort({_id:1});

That will return back all your documents sorted from oldest to newest.

Natural Order

You can also use a Natural Order mentioned above …

db.foo.find().sort({$natural:1});

Again, using 1 or -1 depending on the order you want.

Use .limit()

Lastly, it’s good practice to add a limit when doing this sort of wide open query so you could do either …

db.foo.find().sort({_id:1}).limit(50);

or

db.foo.find().sort({$natural:1}).limit(50);

References
http://stackoverflow.com/questions/4421207/mongodb-how-to-get-the-last-n-records

Install MongoDB on OpenSuse

after install run

sudo nano /etc/mongodb.conf
disable security
# Security settings.
#security:
#  authorization: enabled

the restart service and run with config

mongod --config /etc/mongodb.conf

other commands

db.createUser(
  {
    user: "admin",
    pwd: "admin",
    roles: [ { role: "root", db: "admin" } ]
  }
);
db.createUser(
    {
      user: "mahmood",
      pwd: "12345",
      roles: ["readWrite"]
    }
);

References
https://docs.mongodb.com/v3.0/reference/configuration-options/
http://stackoverflow.com/questions/23943651/mongodb-admin-user-not-authorized
http://stackoverflow.com/questions/35881662/mongodb-error-not-authorized-to-execute-command
https://docs.mongodb.com/manual/tutorial/enable-authentication/
http://stackoverflow.com/questions/23003391/how-do-i-add-an-admin-user-to-mongo-in-2-6

Sessions in Express.js

var session = require('express-session');
const MongoStore = require('connect-mongo')(session);
app.use(session({
    key: 'ERP.Session',
    secret: '310E56DD8E7C',
    resave:true,
    saveUninitialized:true,
    store: new MongoStore({
        url: 'mongodb://localhost/ERP'
    })
}));

Setting Session Variables

req.session.name = 'Napoleon';
req.session['primary skill'] = 'Dancing';

Reading Session Variables

var name = req.session.name;
var primary_skill = req.session['primary skill'];

Updating Session Variables

req.session.skills.push('Baking');
req.session.name = 'Pedro';

Deleting Session Variables

delete req.session.name
delete req.session['primary skill'];

Deleting a Session

req.session.destroy();
req.session.destroy(function() {
  res.send('Session deleted');
});

References
http://expressjs-book.com/index.html%3Fp=128.html
https://github.com/expressjs/session
https://github.com/jdesboeufs/connect-mongo