In SQL I could do something like
SELECT myNum, (myNum+1) as `increment` FROM myTable
effectively doing arbitrary math and other functions and returning those as a field in the result. Can the same be done with MongoDB?
db.test.find({}, {_id:1, myNum:1, increment:function() { return this.myNum + 1;}});
That does not return an "increment" field like I'd expect.
All other related questions I could find on this topic deal with GROUPed queries, which this one is not; I'm just adding a "virtual" field to the document when it's fetched (client-side computed?).
Alternately, this problem seems to be a "map" without a "reduce"; each row has its own calculated field. Is there any way to return the result of a map function as a result/cursor?
The new Aggregation Framework in MongoDB 2.2 allows you to add calculated fields via the $project operator. This isn't quite the same as arbitrary functions because you need to use supported operators, but it does provide a good deal of flexibility.
Here is your example of incrementing _id
s into a new myNum
field:
MongoDB shell version: 2.2.0-rc0
> db.test.insert({_id:123});
> db.test.insert({_id:456});
> db.test.aggregate(
{ $project : {
_id : 1,
'myNum': { $add: [ "$_id", 1]}
}}
)
{
"result" : [
{
"_id" : 123,
"myNum" : 124
},
{
"_id" : 456,
"myNum" : 457
}
],
"ok" : 1
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With