Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List all values of a certain field in mongodb

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]

like image 643
chimpsarehungry Avatar asked Apr 24 '14 15:04

chimpsarehungry


People also ask

How do I display a specific field in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

How can I get distinct values from a field in MongoDB?

To get distinct values, use distinct() in MongoDB. It finds the distinct values for a specified field across a single collection or view and returns the results in an array.

What does find () do in MongoDB?

Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.

What does $all do in MongoDB?

The $all operator selects the documents where the value of a field is an array that contains all the specified elements.


2 Answers

db.collection.distinct('x')

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

like image 119
John Petrone Avatar answered Sep 28 '22 13:09

John Petrone


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

db.collection.find(     { },     { x: 1, y: 0, _id:0 } ) 
like image 31
martskins Avatar answered Sep 28 '22 13:09

martskins