问题
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.
I am new to mongo, db.company.find() --> this will give whole document Which is VERY BIG
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
this is the collection
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---}
],
},
}
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
How can i do this : fast is necessary, data is huge
回答1:
You can use second parameter of .find() method to specify a projection:
db.companies.find({}, { _id: 0, company_name: 1 })
which returns:
{ "company_name" : "gmc" }
{ "company_name" : "tesla" }
...
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" } } }])
which returns:
{ "_id" : null, "company_names" : [ "gmc", "tesla", ... ] }
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).
来源:https://stackoverflow.com/questions/52212165/mongo-get-only-the-name-of-documents-but-not-the-whole-documents