0

and think you in advance for the help. I have recently started using mongoDB for some personal project and I'm interested in finding a better way to query my data.

My question is: I have the following collection:

 {
    "_id" : ObjectId("5dbd77f7a204d21119cfc758"),
    "Toyota" : {
            "Founder" : "Kiichiro Toyoda",
            "Founded" : "28 August 1937",
            "Subsidiaries" : [
                    "Lexus",
                    "Daihatsu",
                    "Subaru",
                    "Hino"
            ]
    }
}

{
    "_id" : ObjectId("5dbd78d3a204d21119cfc759"),
    "Volkswagen" : {
            "Founder" : "German Labour Front",
            "Founded" : "28 May 1937",
            "Subsidiaries" : [
                    "Audi",
                    "Volkswagen",
                    "Skoda",
                    "SEAT"
            ]
    }
}

I want to get the object name for example here I want to return [Toyota, Volkswagen]

I have use this method

var names = {}
db.cars.find().forEach(function(doc){Object.keys(doc).forEach(function(key){names[key]=1})});
names;

which gave me the following result:

{ "_id" : 1, "Toyota" : 1, "Volkswagen" : 1 }

however, is there a better way to get the same result and also to just return the names of the objects. Thank you.

Eng.Riyad
  • 1
  • 3
  • This post has some ideas/code: [How to find a subfield in Mongo without knowing the parent field?](https://stackoverflow.com/questions/58642944/how-to-find-a-subfield-in-mongo-without-knowing-the-parent-field/58644998#58644998). – prasad_ Nov 02 '19 at 13:29
  • Does this answer your question? [Get names of all keys in the collection](https://stackoverflow.com/questions/2298870/get-names-of-all-keys-in-the-collection) – ambianBeing Nov 02 '19 at 14:43

1 Answers1

0

I would suggest you to change the schema design to be something like:

{
  _id: ...,
  company: {
    name: 'Volkswagen',
    founder: ...,
    subsidiaries: ...,
    ...<other fields>...
}

You can then use the aggregation framework to achieve a similar result:

> db.test.find()
{ "_id" : 0, "company" : { "name" : "Volkswagen", "founder" : "German Labour Front" } }
{ "_id" : 1, "company" : { "name" : "Toyota", "founder" : "Kiichiro Toyoda" } }

> db.test.aggregate([ {$group: {_id: null, companies: {$push: '$company.name'}}} ])
{ "_id" : null, "companies" : [ "Volkswagen", "Toyota" ] }

For more details, see:

As a bonus, you can create an index on the company.name field, whereas you cannot create an index on varying field names like in your example.

kevinadi
  • 13,365
  • 3
  • 33
  • 49