database 列出mongodb中某个字段的所有值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23273123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
List all values of a certain field in mongodb
提问by chimpsarehungry
How would I get an array containing all values of a certain field for all of my documents in a collection?
我如何获得一个数组,该数组包含集合中所有文档的某个字段的所有值?
db.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]
“db.collection.ListAllValuesForfield(x)” 结果:[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]
“db.collection.ListAllValuesInArrayField(y)” 结果:[1,2,3,4,5,6,1,2,3,4]
Additionally, can I make this array unique? [1,2,3,4,5,6]
另外,我可以让这个数组独一无二吗?[1,2,3,4,5,6]
回答by John Petrone
db.collection.distinct('x')
db.collection.distinct('x')
should give you an array of unique values for that field.
应该为您提供该字段的唯一值数组。
回答by martskins
This would return an array of docs, containing just it's x value...
这将返回一个文档数组,只包含它的 x 值......
db.collection.find(
{ },
{ x: 1, y: 0, _id:0 }
)
回答by ivanleoncz
Notice:My answer is a fork from the original answer.
注意:我的答案是原始答案的一个分支。
Before any "thumbs up" here, "thumbs up" the accepted answer :).
在任何“竖起大拇指”之前,“竖起大拇指”接受的答案:)。
db.collection.distinct("NameOfTheField")
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/
参考:https: //docs.mongodb.com/manual/reference/method/db.collection.distinct/

