Eli S.
Eli S.

Reputation: 146

Issue trying to query for all "names" on MongoDB?

I'm trying to find all "names" in my collection, and I can't figure out how.

I've tried a bunch of different queries, for example -

db.collectionname.find( { "customers" : { "id" : 1, "name" : 1 } }

nothing really seems to work.

Here is a relevant part of the collection:

{
    "id" : 1,
    "customers" : {
            "id" : 1,
            "name" : "ronald"
    }
}

The rest of my collection is essentially identical. I just need to get a list for all the names, for example, ronald in this case. I have no idea how, would appreciate some help! Thanks in advance.

Upvotes: 0

Views: 37

Answers (1)

Manoj Vadehra
Manoj Vadehra

Reputation: 846

You will need to use aggregations in this case. What you need is to group customers.name and push each name into an array.

Please refer here: https://docs.mongodb.com/manual/reference/operator/aggregation/push/

or if you want unique names only, use addToSet instead of push.

Try this:

db.collectionname.aggregate([{ $group: { _id: null, names: { $push: "$customers.name" } } } ]).pretty()

This will give you an array "names" with all the names stacked together.

Upvotes: 0

Related Questions