Querying for a list of all distinct fields in Mong

2019-08-10 11:58发布

I have a collection where all form data is stored, each form with a different structure, but some forms with overlapping field names. I love mongo for the ease it proves here, allowing me to sort and aggregate totally different data based upon a few small common factors.

Now, for the UI, I need a list of all possible fields in the database so a user can choose which fields to view. I can't seem to find any mongo anything to return a list of fields, except for indexes.

How would I go about this?

2条回答
小情绪 Triste *
2楼-- · 2019-08-10 12:39

There is no native MongoDB functionality that provides this information. MongoDB is completely schemaless and as such you will have to do a full database walk to compile a list of all unique field names.

The only possible workarounds are to store all fields using {field: <field name>, value: <field value>} pairs and run a distinct operation on "field" or to maintain a list of unique field names seperately in the database. Both have significant downsides.

查看更多
叛逆
3楼-- · 2019-08-10 12:51

try this:

 db.collection_keys.distinct("_id")
查看更多
登录 后发表回答