'Find with concat in MongoDB
I have a very simple question on MongoDB.
I have a collection that has 2 fields in each doc. I want to make a find like this:
db.mycoll.find({}, { my_new_f : { $concat : ["$f1", ".", "$f2"]}})
Why such a query is not supported? (Or am I doing something wrong?)
Solution 1:[1]
$concat is an operator that's used with aggregate, not find, and find projections have no support for derived fields like this.
To do this with aggregate you would do something like:
db.mycoll.aggregate({$project: { my_new_f : { $concat : ["$f1", ".", "$f2"]}}})
Solution 2:[2]
From MongoDB version 4.4, aggregation projections are supported for find(). This would now be correct:
db.mycoll.find({}, { my_new_f : { $concat : ["$f1", ".", "$f2"]}})
Solution 3:[3]
db.mycoll.find({$expr:{$eq:["value", {$concat:["$field1", "$field2"]}]}})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JohnnyHK |
| Solution 2 | KalenGi |
| Solution 3 | JON |
