0
0
MongoDBquery~5 mins

Attribute pattern for variable fields in MongoDB

Choose your learning style9 modes available
Introduction
Sometimes, data has fields that change names or appear only sometimes. Using attribute patterns helps find these fields easily.
When you want to find documents with fields that start with a certain word.
When you need to search for fields that have similar names but are not exactly the same.
When your data has flexible or dynamic field names that vary between documents.
When you want to filter documents based on the presence of fields matching a pattern.
When you want to update or analyze fields that follow a naming pattern.
Syntax
MongoDB
db.collection.find({ 'fieldName': { $regex: /pattern/ } })
Use $regex to match field values with a pattern.
To match field names (keys), use $objectToArray and $filter in aggregation.
Examples
Finds users whose name starts with 'Jo'.
MongoDB
db.users.find({ 'name': { $regex: /^Jo/ } })
Finds all fields in documents where the field name starts with 'attr'.
MongoDB
db.collection.aggregate([
  { $project: {
      fields: { $objectToArray: "$$ROOT" }
    }
  },
  { $project: {
      matchedFields: {
        $filter: {
          input: "$fields",
          as: "field",
          cond: { $regexMatch: { input: "$$field.k", regex: /^attr/ } }
        }
      }
    }
  }
])
Sample Program
This inserts products with variable attribute fields starting with 'attr'. Then it finds and lists only those attribute fields for each product.
MongoDB
db.products.insertMany([
  { _id: 1, attrColor: "red", attrSize: "M", price: 10 },
  { _id: 2, attrColor: "blue", price: 15 },
  { _id: 3, attrWeight: "2kg", price: 20 }
])

db.products.aggregate([
  { $project: {
      attributes: {
        $filter: {
          input: { $objectToArray: "$$ROOT" },
          as: "field",
          cond: { $regexMatch: { input: "$$field.k", regex: /^attr/ } }
        }
      }
    }
  }
])
OutputSuccess
Important Notes
MongoDB stores documents with flexible fields, so field names can vary.
To search by field names, use aggregation with $objectToArray to convert fields into key-value pairs.
Regular expressions ($regex) help match patterns in strings, including field names.
Summary
Use $regex to find values matching patterns.
Use $objectToArray and $filter in aggregation to find fields with names matching patterns.
This helps handle data with variable or dynamic field names.