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
Concatenate with condition in MongoDB?
To concatenate with condition in MongoDB, use $cond with $concat in an aggregation pipeline. This allows you to perform string concatenation based on specific conditions and filter results accordingly.
Syntax
db.collection.aggregate([
{
"$redact": {
"$cond": [
{ "$eq": [{ "$concat": ["$field1", "$field2"] }, "targetValue"] },
"$$KEEP",
"$$PRUNE"
]
}
}
]);
Sample Data
db.demo745.insertMany([
{ "Value1": "100", "Value2": "100" },
{ "Value1": "40", "Value2": "50" },
{ "Value1": "13", "Value2": "45" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5eae6419a930c785c834e554"),
ObjectId("5eae6421a930c785c834e555"),
ObjectId("5eae6429a930c785c834e556")
]
}
Display all documents from the collection ?
db.demo745.find();
{ "_id": ObjectId("5eae6419a930c785c834e554"), "Value1": "100", "Value2": "100" }
{ "_id": ObjectId("5eae6421a930c785c834e555"), "Value1": "40", "Value2": "50" }
{ "_id": ObjectId("5eae6429a930c785c834e556"), "Value1": "13", "Value2": "45" }
Example: Filter Documents by Concatenated Values
Find documents where concatenating Value1 and Value2 equals "1345" ?
db.demo745.aggregate([
{
"$redact": {
"$cond": [
{ "$eq": [{ "$concat": ["$Value1", "$Value2"] }, "1345"] },
"$$KEEP",
"$$PRUNE"
]
}
}
]);
{ "_id": ObjectId("5eae6429a930c785c834e556"), "Value1": "13", "Value2": "45" }
How It Works
-
$concatcombines Value1 and Value2 into a single string -
$eqchecks if the concatenated result equals the target value "1345" -
$$KEEPincludes the document if condition is true -
$$PRUNEexcludes the document if condition is false
Conclusion
Use $redact with $cond and $concat to filter documents based on concatenated field values. This approach efficiently combines string operations with conditional logic in MongoDB aggregation pipelines.
Advertisements
