List all values of a certain field in mongodb

MongodbMongodb QueryDatabase

Mongodb Problem Overview


How would I get an array containing all values of a certain field for all of my documents in a collection?

db.collection:

{ "_id" : ObjectId("51a7dc7b2cacf40b79990be6"), "x" : 1 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990be7"), "x" : 2 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990be8"), "x" : 3 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990be9"), "x" : 4 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bea"), "x" : 5 }

"db.collection.ListAllValuesForfield(x)" Result: [1,2,3,4,5]

Also, what if this field was an array?

{ "_id" : ObjectId("51a7dc7b2cacf40b79990be6"), "y" : [1,2] }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990be7"), "y" : [3,4] }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990be8"), "y" : [5,6] }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990be9"), "y" : [1,2] }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bea"), "y" : [3,4] }

"db.collection.ListAllValuesInArrayField(y)" Result: [1,2,3,4,5,6,1,2,3,4]

Additionally, can I make this array unique? [1,2,3,4,5,6]

Mongodb Solutions


Solution 1 - Mongodb

db.collection.distinct('x')

should give you an array of unique values for that field.

Solution 2 - Mongodb

This would return an array of docs, containing just it's x value...

db.collection.find(
    { },
    { x: 1, y: 0, _id:0 }
)

Solution 3 - Mongodb

Notice: My answer is a fork from the original answer.

Before any "thumbs up" here, "thumbs up" the accepted answer :).


db.collection.distinct("NameOfTheField")

> Finds the distinct values for a specified field across a single collection or view and returns the results in an array.

Reference: https://docs.mongodb.com/manual/reference/method/db.collection.distinct/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionchimpsarehungryView Question on Stackoverflow
Solution 1 - MongodbJohn PetroneView Answer on Stackoverflow
Solution 2 - MongodbmartskinsView Answer on Stackoverflow
Solution 3 - MongodbivanleonczView Answer on Stackoverflow