Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to return a calculated field from a MongoDB query?

Tags:

mongodb

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?

like image 713
MidnightLightning Avatar asked Aug 10 '12 21:08

MidnightLightning


1 Answers

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 _ids 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
}
like image 68
Stennie Avatar answered Oct 10 '22 10:10

Stennie