omkarstha
omkarstha

Reputation: 53

How to get all the values of a given key in the whole collection in mongodb

One of my mongodb collection is

{_id: "1", username: "one"}
{_id: "2", username: "two"}
{_id: "3", username: "three"}
......
{_id: "50", username: "fifty"}

I want to query the collection to get the values of all the "username" keys in whole collection as:

["one","two","three",.... "fifty"]

I've tried this so far and it yields the results as:

db.users.find({}, { username: 1, _id: 0 })
// output: [ { username: "one" }, { username: "two" }, ..... ]

Upvotes: 1

Views: 1019

Answers (1)

hhharsha36
hhharsha36

Reputation: 3349

Make use of the $group stage via Aggregation and group all the documents in the collection and push the required value to an array.

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

If you want distinct values of usernames, replace $push with $addToSet instead.

Upvotes: 2

Related Questions