Introduction
Sometimes, data has fields that change names or appear only sometimes. Using attribute patterns helps find these fields easily.
db.collection.find({ 'fieldName': { $regex: /pattern/ } })db.users.find({ 'name': { $regex: /^Jo/ } })db.collection.aggregate([
{ $project: {
fields: { $objectToArray: "$$ROOT" }
}
},
{ $project: {
matchedFields: {
$filter: {
input: "$fields",
as: "field",
cond: { $regexMatch: { input: "$$field.k", regex: /^attr/ } }
}
}
}
}
])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/ } }
}
}
}
}
]){
$project: {
filteredFields: {
$filter: {
input: { $objectToArray: "$ROOT" },
as: "field",
cond: { $regexMatch: { input: "$$field.k", regex: /^a/ } }
}
}
}
}{
$project: {
scores: {
$filter: {
input: { $objectToArray: "$ROOT" },
as: "field",
cond: { $regex: "score", input: "$$field.k" }
}
}
}
}Pass the test and this pattern moves unknown