skip to Main Content

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.

2

Answers


  1. try {
      const data = await Model.find(); // use your model name here, this will store every document in an array
      const result = [];
      data.forEach((item) => result.push(item.name)); //for every document in data array, we store the name onto the result array
      return res.status(200).send(result);
    } catch (error) {
      return res.status(500).send(error);
    }
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search