5

I just installed Robo3T( previously named robomongo), which has a GUI for mongo db. I want to add a custom function to help me get the last N documents in normal order, the query statement is like this:

db.getCollection('i1801').find().skip(db.getCollection('i1801').count() - 1200)

And I found from stackoverflow(mongodb: how to get the last N records?), this can be written as a function like this:

function last(N) {
    return db.collection.find().skip(db.collection.count() - N);
}

And I go back to my Robo3T, trying to add a custom function last(), but didn't work, nothing showed up under function tab.

I have attached some screen captures illustrating this issue:

Trying to add a custom function

Created a custom function and saved

After save, nothing happened

After I clicked save button, nothing happened, still no functions under function tab. And the log shows function last created, and function tab being refreshed. Here is the logs

So, how can I add a last function here?

StayFoolish
  • 531
  • 1
  • 12
  • 29

2 Answers2

4

Tried the steps you listed, it worked for simple find statements. When I added the 'skip', the save failed. Even updating an existing function didn't work. Maybe an issue with Robo? I dont know.

Anyway, to add the function in Robo3t

  1. Right click collection
  2. Select Open Shell
  3. On the shell type the following

db.system.js.save(
   {
     _id: "last",
     value : function last(x) { return db.test.find().skip(db.test.count() - x); }
   }
)

Lastly, Run the script and refresh Function folder.

trashvin
  • 545
  • 1
  • 5
  • 14
  • Thanks, now the function has been created, but I might have to ask some dumb questions since I don't know js or familiar with Robo3T. After created the function `last`, how can I use it. I've tryied to run `last(5)` , `db.getCollection('rb1801').last(5)`, or `db.last(5)` all don't work. Any advice? – StayFoolish Sep 27 '17 at 01:34
  • For starters you can look into this post : https://stackoverflow.com/questions/18185192/call-stored-function-in-mongodb – trashvin Sep 27 '17 at 02:21
2

For calling function:

db.loadServerScripts();
callyourfunction();

  1. Right click on collection
  2. Click on open shell
    https://i.stack.imgur.com/YTiGc.jpg
  3. In shell run db.loadServerScripts();
    https://i.stack.imgur.com/BDTBT.jpg
  4. call user function like: addTwo(2,5);
    https://i.stack.imgur.com/EujGo.jpg

NOTE :: For seen output, Make sure your function should be a return value

Community
  • 1
  • 1
HSP
  • 345
  • 4
  • 4