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",
},
]