Search code examples
javascriptmongodbmongoose

How can I get all values from a specific key in mongoose?


I got a few documents in mongoose that looks something like this:

[
    {
        _id = "...",
        name = "abc123",
        colors = [1, 2, 3]
    },
    {
        _id = "...",
        name = "def431",
        colors = [4, 2, 1]
    },
    {
        _id = "...",
        name = "htl534",
        colors = [3, 5, 7]
    },
    {
        _id = "...",
        name = "lwq154",
        colors = [9, 1, 4]
    }
]

From these documents I'd like to get an array with all the values from the keys named name, it would look something like this: ["abc123", "def431", "htl534", "lwq154"]. How could I achive this? I thought about using some sort of querys or some find function, but I can't seem to figure it out.


Solution

  • I think you can use an aggregate query and avoid loop using a simple $group like this:

    db.collection.aggregate([
      {
        "$group": {
          "_id": null,
          "result": {
            "$push": "$name"
          }
        }
      }
    ])
    

    Example here

    With this query you are adding all values into an array calling result. You can also use $addToSet to avoid duplicates. Example here