Does anyone know if there is a way to query MongoDB and have only certain fields returned by using a regex as part of the projection?
For example: Given a collection having arbitrary field names, how might I query the collection and only return field names matching the regex '^foo'.
Possibly something like this?
db.mycollection.find({},{$regex:"^foo"})
Thanks. Brent.
MongoDB provides the functionality to search a pattern in a string during a query by writing a regular expression. A regular expression is a generalized way to match patterns with sequences of characters. MongoDB uses Perl compatible regular expressions(PCRE) version 8.42 along with UTF-8 support.
Adding a new projection queryIn the MongoDB integration, click the Collections to Replicate tab. Navigate to the desired collection. Click the checkbox to the left of the collection to set it to replicate.
In MongoDB, projection means selecting only the necessary data rather than selecting whole of the data of a document. If a document has 5 fields and you need to show only 3, then select only 3 fields from them.
One can use projection with db. collection. find() method.
I think you need to break down the process into two pieces, the first one is retrieving the fields names from MongoDB.
Then the second piece is that you can run the regex on the result, and from there you can query the DB with the right fields.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With