ozomer / node-red-contrib-mongodb2

MongoDB driver node for Node-RED
Apache License 2.0
15 stars 19 forks source link

Using some sort and limit in msg. #13

Closed otakuf closed 7 years ago

otakuf commented 7 years ago

Hello!

Can you explain how i can make some sort with mongodb2? In node-red-node-mongodb i just use simple case:

msg.payload = {};
msg.sort = { "_id": -1 };
msg.limit = 1;
return msg;

This return last one record from db.

ozomer commented 7 years ago

Hmm.. this is a good question, because the official API does not mention that the function can actually receive more than one parameter (i.e. query). If you look at the code, you can see it may accept 2 paramters: query, options (it also does some ugly checks to see if the options parameters is actually a fields filter, but let's not dive into this issue). The options parameter can receive a sort option. So, you should do something like:

msg.payload = [{}, {
  "sort": {
    "_id": -1
  },
  "limit": 1
}];

This will run the function-call: find({}, { "sort": { "_id": -1 }, "limit": 1 }); that you want.

P.S. If your limit is 1, you can simply use findOne(query, options) instead of find(...).toArray()