0

In the command line tool mongosh, is it possible to add a custom function and I can use it this way: >db.somecollection.myCustomFunc()

8

1 Answer 1

0

Based on your comments, I have no idea what you are looking for.

But purely based on your question, the solution is this one:

Object.defineProperty(db.getSiblingDB('so').getCollection("somecollection"), 'giveMeFive', {
   enumerable: true,
   writable: false,
   configurable: false,
   value: () => {return 5}
});

and the just use it

use so
db.somecollection.giveMeFive()
5

Or another example:

Object.defineProperty(db.getSiblingDB('so').getCollection("somecollection"), 'insertTwo', {
   enumerable: true,
   writable: false,
   configurable: true,
   value: (x) => { 
      db.getSiblingDB('so').getCollection("somecollection").insertMany([x, x]); 
      return 'OK'; 
   }
});

use so
db.somecollection.insertTwo({ val: 3 })
OK

db.somecollection.find()
[
  { _id: ObjectId("63ceb12b2545bff4a24f2872"), val: 3 },
  { _id: ObjectId("63ceb12b2545bff4a24f2873"), val: 3 }
]

But as written in my comment, when you restart the shell then your property gets deleted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.