Query mongodb with wildcard on keys

Dear community,

is there a way to query collections with wildcard on attributes (keys)?

If we have the collection below, and I would like to retrieve all entries having attributes with a key containing “_address”, would there be any way to achieve this in a query?:

[
  {
    name: "contact_1",
    business_address: "street 1"
  },
  {
    name: "contact_2",
    personal_address: "street 2"
  },
  {
    name: "contact_3",
    number: 123456
  }
]

The query should lead to retrieval of contact_1 and contact_2.

Take a look at

Personally, I would change the schema using the attribute pattern, Building with Patterns: The Attribute Pattern | MongoDB Blog, to something like:

[
  {
    "name": “contact_1” ,
    "tags": [ "business" ] ,
    "address" : “street 1”
  },
 {
    "name": “contact_2”,
    "tags" : [ "personnel" , "family" ]
    "address" : “street 2”
  },
  {
    "name": “contact_3”,
    "tags" : [ "personnel" , "friend" ] ,
    "number" : 123456
  }
]

One of the advantages is that the sub-document schema is consistent. This helps when coding. For example, the same simpler code can be used to print an address. Otherwise you need logic to determine if you want to access the field business_address or personal_address. This also helps reduce the number of indexes since the fields have the same name. Otherwise you need an index for business_address and one for personal_address.

1 Like