2

I have an aggregator setup and need to run a vanilla JS function call to manipulate the data prior to using the $out stage.

Here's what I have so far:

myFunc = (x) => {
    newObj = {
        prop_id: x.prop_id,
        newValue: x.file_as_name
    }
    return newObj;
}

(async () => {

    const dbURL = `mongodb://localhost:27017`
    const MongoClient = require('mongodb').MongoClient;
    let client = await MongoClient.connect(dbURL, { useNewUrlParser: true, useUnifiedTopology: true })


    let agg = [
        { $match: {} },
        { $limit: 5 },
        {
            '$replaceRoot': {
                'newRoot': {
                    '_id': '$$ROOT._id',
                    'prop_id': myFunc('$$ROOT')
                }
            }
        },


        { $out: 'test' }
    ]


    try {
        let rex = await client.db('mydb').collection('mycollection').aggregate(agg)

    } catch (e) {
        console.log(e);
    }


})()

The documents right now end up with:

{
  "_id": "5ed80b8311ad182ed7594d3d",
  "newObj": {
    "prop_id": null,
    "newValue": null
  }
}

How can I make it so that myFunc is able to access the data contained with $$ROOT that gets passed to it?

Justin Young
  • 2,393
  • 3
  • 36
  • 62
  • 1
    Check the answer on this post: https://stackoverflow.com/questions/25865788/call-function-inside-mongodbs-aggregate – fedeteka Jun 05 '20 at 23:20

1 Answers1

0

Earlier there is $where operator to execute a JavaScript function in MongoDB query language, but usually it's discouraged to use it cause executing .Js functions can highly impact performance & $expr operator from version 3.6 has replaced most chances of using $where.

From documentation :

The use of JavaScript with scope for the $where function has been deprecated since version 4.2.1.

Starting MongoDB version 4.4 you'll a new operator $function to define custom aggregation functions or JavaScript expressions.

For now, I believe you don't need to use any of these operators for your scenario :

let agg = [
  { $match: {} },
  { $limit: 5 },
  {
    $replaceRoot: {
      newRoot: {
        _id: "$$ROOT._id",
        prop_id: {
            prop_id: "$$ROOT.prop_id",
            newValue: "$$ROOT.file_as_name"
        }
      }
    }
  },
  { $out: "test" }
];
whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46