ozomer / node-red-contrib-mongodb2

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

Examples for msg.payload #46

Open braghettos opened 3 years ago

braghettos commented 3 years ago

Hi! I'm looking for examples in order to implement something like this:

var groups = {} // init group object
var currentGroupKey;
var groupInterval = 5 * 60 * 1000; // Five minutes in milliseconds

var cursor = db.collection("documents").find({}).sort({date: 1});

cursor.on('data', function(doc) {
  var timestamp = doc.date.getTime();

  if (currentGroupKey != null && currentGroupKey + groupInterval >= timestamp) {
    // add it to current group
    groups[currentGroupKey].push(doc);
  } else {
    // create a new group
    groups[timestamp] = [doc];
    currentGroupKey = timestamp;
  }
});
cursor.once('end', function() {
  // This is called after last document is read
  console.log(groups); // print your grouped documents
  db.close();
});

but I'm not able to find any examples on how to write the msg.payload. Could you please help me?

Many thanks,

Diego

jomel commented 3 years ago

Read the source code for this very package... https://github.com/ozomer/node-red-contrib-mongodb2/blob/70a7d7801db974b6d486be182d740adcd978cf9d/mongodb/mongodb.js#L339

But WHY would you want to do that??? Just use a "find.forEach" from this package and then process/group/batch the returned documents any way you wish using other nodeRed nodes (eg https://flows.nodered.org/node/node-red-contrib-batcher with "maxDelay" set to 5 minutes)

I can't help any more as I stopped using NodeRed.

braghettos commented 3 years ago

Hi @jomel ,

my issue is to aggregate documents with the closest timestamps. I couldn't be able to find any examples on the msg.payload format even for a simple "find.forEach" as you said, even looking at your latest link.

I will experiment with these examples: https://github.com/ozomer/node-red-contrib-mongodb2/issues/4