In the command line tool mongosh, is it possible to add a custom function and I can use it this way:
>db.somecollection.myCustomFunc()
1 Answer
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.
mongosh
, have also a careful look at Script Limitations and Database operations not always working in ClassesObject.getOwnPropertyDescriptors(db.somecollection)
gives a big output. I think you could add some properties.