MONGO仅获得文档名称,而不是整个文档 [英] MONGO get only the name of documents but not the whole documents
问题描述
查询mongo仅查找名称:以一种快速的方式进行,即我不想获取每个文档,然后从每个文档中获取名称.
query mongo to find only the names : in such a way that it should be fast, ie i don't want to get each document and then get the name from each of them.
我是mongo的新手,db.company.find()->这将给出整个文件,非常大
I am new to mongo, db.company.find() --> this will give whole document Which is VERY BIG
注意;我已将索引用于公司名称&也是独特的条件.o->我认为这应该可以帮助我快速找到公司名称,很容易但是我不知道
NOTE ; i have used indexing to the company name & also the unique condition too. soo --> i think it should help me finding the company name fast and easily , BUT i don't know how
这是收藏集
collection company : --> list of companies in the collection
{
{
"_id": "5b8ed214b460e7c17c5a33f9",
"company_location": "USA",
"company_name": "tesla", -----> COMPANY NAME: TESLA
"cars":
[
{---car 1---} ,
{---car 2---} ,
{---car n---}
],
},
{
"_id": "5b8ed214b460e7c17c5a33f9",
"company_location": "USA",
"company_name": "gmc", -----> COMPANY NAME :GMC
"cars":
[
{---car 1---} ,
{---car 2---} ,
{---car n---}
],
},
{
"_id": "5b8ed214b460e7c17c5a33f9",
"company_location": "USA",
"company_name": "bmw", -----> COMPANY NAME:BMW
"cars":
[
{---car 1---} ,
{---car 2---} ,
{---car n---}
],
},
{
"_id": "5b8ed214b460e7c17c5a33f9",
"company_location": "USA",
"company_name": "audi", -----> COMPANY NAME: AUDI
"cars":
[
{---car 1---} ,
{---car 2---} ,
{---car n---}
],
},
}
所以,我只想要公司名称列表,而不是使用 db.companies.find()
的整个公司集合.->然后遍历查找它们的名称
So I just want the list of company names, and not the whole company collection using db.companies.find()
. --> and then finding the names of each of them by traversing it
我该怎么做:必须快速,数据量巨大
推荐答案
You can use second parameter of .find()
method to specify a projection:
db.companies.find({}, { _id: 0, company_name: 1 })
返回:
{ "company_name" : "gmc" }
{ "company_name" : "tesla" }
...
或者您可以使用Aggregation Framework来获取带有名称数组的单个文档:
Or you can use Aggregation Framework to get single document with an array of names:
db.companies.aggregate([{ $group: { _id: null, company_names: { $push: "$company_name" } } }])
返回:
{ "_id" : null, "company_names" : [ "gmc", "tesla", ... ] }
如果在 company_name
上有索引,第一个应该是最快的方法.在这种情况下,您的查询不需要扫描集合,而只能使用索引来获取查询的数据(已覆盖查询).
First one should be the fastest way if you have an index on company_name
. In that case your query don't need to scan collection and can use only index to get queried data (covered query).
这篇关于MONGO仅获得文档名称,而不是整个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!