Search code examples
javascriptarraysmongodbmongodb-shell

How can I change an array of documents to an array of values in MongoDB shell?


So, basically, I have this array of IDs:

> arrayDeptID
[
    {
        "departamento_id" : 0
    },
    {
        "departamento_id" : 2
    },
    {
        "departamento_id" : 5
    },
    {
        "departamento_id" : 6
    }
]

And I want to transform it to an array that contains only the values on the document field departamento_id, something like this:

[0, 2, 5, 6]

Is there any way to do it in MongoDB shell?


Solution

  • Use JavaScipt .map():

    arrayDeptID.map(function(el) { return el.departamento_id })
    

    Then MongoDB shell is a JavaScript REPL. So just about all ECMAScript built-in functions exist. It is built on V8, so whatever is in there is generally in here too.