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

后端 未结 1 1604
悲&欢浪女
悲&欢浪女 2021-02-04 08:33

In SQL I could do something like

SELECT myNum, (myNum+1) as `increment` FROM myTable

effectively doing arbitrary math and other functions and

1条回答
  •  南方客
    南方客 (楼主)
    2021-02-04 09:00

    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
    }
    

    0 讨论(0)
提交回复
热议问题