BrentR
BrentR

Reputation: 928

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.

Upvotes: 7

Views: 2301

Answers (1)

Baraa Al-Bourghli
Baraa Al-Bourghli

Reputation: 126

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.

Upvotes: 2

Related Questions