mongodbjacksonjsonpath

Querying only the field name in Mongodb


Consider a document in Mongodb for eg:

{name:"Josh","address":{"street_no":34,"district":"Gurgaon","pincode":"1234xyz"}}

How do I fetch the field names(not the values)by querying ? Is it possible? For example I need to write a query which will return me "name","address","street_no","district" and "pincode" as the fields in the Mongodb document.


Solution

  • You can only retrieve values and query on values. You'd need to restructure your data to be more like this: {"key": "street_no", "value": 34}. Of course, that could dramatically affect your indexing and other searches that you may want to do (and certainly can reduce the readability of a document structure).

    Unless you've got hundreds of fields and a very large document, I'd suggest you just return the values rather than trying to get MongoDB to return just the field names.

    If you really need field names, you could store them in an array as part of the document if you wanted (if the key/value suggestion didn't seem to fit your other requirements). While it's double storage, this type of technique is sometimes necessary with MongoDB.

    You can always check for the existence of a given field using $exists (documentation).