是否可以从MongoDB查询返回计算字段? [英] Is it possible to return a calculated field from a MongoDB query?

查看:204
本文介绍了是否可以从MongoDB查询返回计算字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在SQL中,我可以做类似

In SQL I could do something like

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

有效地执行任意数学和其他函数,并将其作为结果中的字段返回. MongoDB可以做到吗?

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.

在该主题上我能找到的所有其他相关问题都与GROUPED查询有关,而这不是.在获取文档时(客户端计算了?),我只是在文档中添加了一个虚拟"字段.

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?).

或者,这个问题似乎是一个没有减少"的地图".每行都有自己的计算字段.有什么方法可以将map函数的结果作为结果/游标返回?

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?

推荐答案

新的聚合框架在MongoDB 2.2中可以通过 $ project 添加计算字段操作员.这与任意函数不太一样,因为您需要使用受支持的运营商,但确实提供了很大的灵活性.

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.

这是您将_id递增到新的myNum字段中的示例:

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
}

这篇关于是否可以从MongoDB查询返回计算字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆