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
MongoDB query to find records with keys containing dots?
To find MongoDB records containing field names with dots, use the aggregation pipeline with $addFields, $objectToArray, and $filter operators. The $indexOfBytes operator detects dot characters in field names.
Syntax
db.collection.aggregate([
{
$addFields: {
result: {
$filter: {
input: { $objectToArray: "$fieldName" },
cond: {
$ne: [ { $indexOfBytes: [ "$$this.k", "." ] }, -1 ]
}
}
}
}
},
{
$match: {
$expr: {
$ne: [ { $size: "$result" }, 0 ]
}
}
},
{
$project: {
result: 0
}
}
]);
Sample Data
db.demo364.insertMany([
{
"details": {
"details1.otherdetails.Name": {"FirstName": "Chris"}
}
},
{
"details": {
"details1.otherdetails.Name": {"FirstName": "David"}
}
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e57d485d0ada61456dc936d"),
ObjectId("5e57d486d0ada61456dc936e")
]
}
Example
Find all documents where field names contain dots ?
db.demo364.aggregate([
{
$addFields: {
result: {
$filter: {
input: { $objectToArray: "$details" },
cond: {
$ne: [ { $indexOfBytes: [ "$$this.k", "." ] }, -1 ]
}
}
}
}
},
{
$match: {
$expr: {
$ne: [ { $size: "$result" }, 0 ]
}
}
},
{
$project: {
result: 0
}
}
]);
{ "_id": ObjectId("5e57d485d0ada61456dc936d"), "details": { "details1.otherdetails.Name": { "FirstName": "Chris" } } }
{ "_id": ObjectId("5e57d486d0ada61456dc936e"), "details": { "details1.otherdetails.Name": { "FirstName": "David" } } }
How It Works
-
$objectToArrayconverts the object into key-value pairs -
$indexOfBytessearches for dot character in each key name -
$filterkeeps only keys containing dots (where index ? -1) -
$matchreturns documents with at least one matching key -
$projectremoves the temporary result field
Conclusion
Use aggregation pipeline with $objectToArray and $indexOfBytes to identify MongoDB documents containing field names with dots. This approach efficiently filters records based on field name patterns.
Advertisements
