Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query mongodb with a regex in the projection?

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.

like image 460
BrentR Avatar asked Jan 06 '14 18:01

BrentR


People also ask

Can I use regex in MongoDB query?

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.

How do I add a projection in MongoDB query?

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.

What is a projection in MongoDB queries?

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.

Which of the following command is used for projection MongoDB?

One can use projection with db. collection. find() method.


1 Answers

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.

like image 155
Baraa Al-Bourghli Avatar answered Oct 18 '22 11:10

Baraa Al-Bourghli