Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Find when the keys are unknown in MongoDB?
To find documents when the keys are unknown in MongoDB, use $addFields with $objectToArray to convert documents into key-value arrays, then search through the values dynamically.
Syntax
db.collection.aggregate([
{ "$addFields": {
"arrayField": { "$objectToArray": "$$ROOT" }
}},
{ "$match": { "arrayField.v.fieldName": "searchValue" }},
{ "$project": { "arrayField": 0 }}
])
Sample Data
db.demo375.insertMany([
{
"details": {
"Name": "John",
"Age": 23
}
},
{
"details": {
"Name": "David",
"Age": 21
}
},
{
"details": {
"Name": "David",
"Age": 22
}
}
]);
Display all documents to verify the structure ?
db.demo375.find();
{ "_id" : ObjectId("5e5a0ae42ae06a1609a00b06"), "details" : { "Name" : "John", "Age" : 23 } }
{ "_id" : ObjectId("5e5a0ae42ae06a1609a00b07"), "details" : { "Name" : "David", "Age" : 21 } }
{ "_id" : ObjectId("5e5a0ae42ae06a1609a00b08"), "details" : { "Name" : "David", "Age" : 22 } }
Example: Find Documents with Unknown Key Structure
Search for documents containing "David" without knowing the exact field path ?
db.demo375.aggregate([
{ "$addFields": {
"UnknownKeys": { "$objectToArray": "$$ROOT" }
}},
{ "$match": { "UnknownKeys.v.Name": "David" }},
{ "$project": { "UnknownKeys": 0 }}
]);
{ "_id" : ObjectId("5e5a0ae42ae06a1609a00b07"), "details" : { "Name" : "David", "Age" : 21 } }
{ "_id" : ObjectId("5e5a0ae42ae06a1609a00b08"), "details" : { "Name" : "David", "Age" : 22 } }
How It Works
-
$objectToArrayconverts each document into an array of key-value pairs -
$$ROOTrepresents the entire document being processed -
UnknownKeys.vaccesses the value portion of each key-value pair -
$projectremoves the temporary UnknownKeys field from final output
Conclusion
Use $objectToArray with $$ROOT to search documents when field names are dynamic or unknown. This technique converts documents to searchable key-value arrays, enabling flexible queries across varying document structures.
Advertisements
