简体   繁体   中英

Mongo shell javascript array extensions

So I am trying to use javascript array extensions (Array.prototype functions) in the mongodb shell and they don't seem to be defined. I think this is ok for me but I would very much like to use them in actual quires (namely group) and in map-reduce. I am using mognodb version 2.4.10. It says here that 2.4 plus should have the ES5 array extensions. Are they just not available in shell?

Specifically the fill method does not work

test = [1, 2, 3, 4]
test.fill(0)

fails saying TypeError: Object 1,2,3 has no method 'fill'

Why isn't Array.fill() working?

Array.fill() is a proposed part of the ES6 spec (still experimental as at August, 2014), so is definitely not supported out-of-the-box in the MongoDB 2.4 or 2.6 mongo shell or server-side JavaScript.

What are the new ES5 array methods?

2.4 plus should have the ES5 array extensions

There are nine new Array methods in ES5: indexOf , lastIndexOf , every , some , forEach , map , filter , reduce , and reduceRight .

You can find out more about available Array methods in the ES5 spec .

Is there a workaround to use Array.fill()?

If you really want to use this function there happens to be a reference implementation of Array.fill() in the Mozilla Developer Network documentation. You could embed this code in your Map-Reduce functions or store a server-side JavaScript function in system.js as appropriate.

NOTE: In general, use of server-side JavaScript in MongoDB is discouraged for performance reasons. Server-side functions will add overhead to all server-side JavaScript contexts, so if you only need this for a specific or infrequently used Map-Reduce job you would probably be better embedding the code.

Extending the mongo shell

It is also possible to extend the mongo shell with custom JavaScript functions using one of several methods:

  • Paste JavaScript code into an active mongo shell session.
  • Use load() to load and evaluate the contents of a JavaScript file.
  • Save JavaScript code into ~/.mongorc.js to have this loaded when you start the mongo shell.
  • Use db.loadServerScripts() to load all JavaScript functions saved in the server-side system.js collection for the current database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM