0

Is it possible to find objects in a collection by a certain substring, if this substring may be contained in any field of this collection.

For example, my substring is "aa". And I have 2 collections:

{
    "_id" : ObjectId("5788a3e4ffcf140b5955eead"),
    **"Address" : "aaBB",**
    "FirstName" : "First",
    "SecondName" : "Second"
} 

{
    "_id" : ObjectId("7788a3e4fhcf140098725eead"),
    "Address" : "bb",
    "FirstName" : "First",
    **"SecondName" : "aaAA"**
} 

So, what query should I use to get these 2 records?

Thank you

Community
  • 1
  • 1
Sviatlana
  • 1,728
  • 6
  • 27
  • 55
  • @chridam , I need search across all fields in a collection. But in this answer it is searched by the certain field A – Sviatlana Jul 15 '16 at 09:42
  • 1
    Use `$or` together with the regex i.e. `db.collection.find({ "$or": [ { "Address": /aa/ }, { "SecondName": /aa/ } ] })` – chridam Jul 15 '16 at 09:51
  • 1
    @SSDMS Sounds ideal, will reopen but cannot close again as vote to do so will be expended. – chridam Jul 15 '16 at 10:17

1 Answers1

4

I found solution for my case:

db.getCollection('ContractAnswers').find({$where:"JSON.stringify(this).indexOf('aa')!=-1"})
Sviatlana
  • 1,728
  • 6
  • 27
  • 55