Create new collection from an aggregation array within a serverless function

Hi all - Within a serverless function, I’m loading data from a collection (readColl), then selecting two random values using

readColl.aggregate([ { $sample: { size: 2 } } ])

readColl.aggregate returns an array of objects. I would like to then writeColl.insertMany() and populate a new collection.

Within the MongoDb function shell, I cannot extract the objects returned from the readColl.aggregate() array. I’m getting a error message:

uncaught promise rejection: mongodb insert: argument must be an array

How do I take the array of objects (documents) returned by readColl.aggregate() and pass them to writeColl.insertMany() ? Thank you so much for your help.

MongoDb function:

exports = function(payload, response) {
  const mongodb = context.services.get("mongodb-atlas");
  
  const readColl = mongodb.db("temp_db").collection("read_coll")
  const writeColl = mongodb.db("temp_db").collection("write_coll")
  
  const rand = readColl.aggregate([ { $sample: { size: 2 } } ])
  
  writeColl.insertMany(rand)
  
  return rand
}

read_coll:

[
    {
      "1": "A",
    },
    {
      "2": "B",
    },
    {
      "3": "C",
    },
    {
      "4": "D",
    },
    {
      "5": "E",
    },
    {
      "6": "F",
    },
    {
      "7": "G",
    },
]

Found a solution. Instead of deleting my question, best to post the solution correct?

I build an aggregation pipeline and then inserted the pipeline into function. The two-stage pipeline uses $sample followed by $merge.

exports = function(payload, response) {
  const mongodb = context.services.get("mongodb-atlas");
  
  const readColl = mongodb.db("temp_db").collection("temp_read")
  const writeColl = mongodb.db("temp_db").collection("temp_write")
  
  return readColl.aggregate([
  {
    $sample:
      {
        size: 2,
      },
  },
  {
    $merge:
      {
        into: 'temp_write',
        on: "_id",
        whenMatched: "replace",
        whenNotMatched: "insert",
      },
  },
])
}
1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.