Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Query - limit fields where name matches pattern

I've read everything I can find about Projection in MongoDB. I'm hoping this is simple and I just missed it due to the overwhelming flexibility of Mongo queries.

In our MySql database, we've adopted a business practice of having "hidden" fields be prefixed with an underscore. Our application knows how to hide these fields.

Moving some data to mongo, I need to retrieve the documents, with ALL underscore prefixed fields omitted. Of course this should be done in the query rather than document manipulation after retrieval.

All the operators like $regex, $in, $all seem to apply to values. I need to build a projection that ignores an unknown number of fields based on their name. Something like:

db.coll.find({}, {"_*": 0})

Of course that doesn't work, but explains the idea.

I should note: this is necessary because the documents are editable by our application users, so I have no idea what the schema might look like. I do know our "internal" fields are prefixed with an _, and those need to be protected by omission from the editor.

Hope it's easy...

like image 842
hikaru Avatar asked Mar 25 '26 16:03

hikaru


1 Answers

You can have a separate field as hidden_fields or something. See the following schema.

{_id: 'myid1', hidden_fields: {"_foo": "bar", "_foo2": "bar2"}, key1: value1 ...}

Now on the basis of above schema just do,

db.collection.find({ ... }, {hidden_fields: 1})

This will display hidden fields. Also you can have indexes on fields within sub documents so no loss in terms of performance as well.

like image 145
Sushant Gupta Avatar answered Mar 27 '26 06:03

Sushant Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!