在MongoDB中执行搜索/投影时,如何重命名字段? [英] How do I rename fields when performing search/projection in MongoDB?

查看:224
本文介绍了在MongoDB中执行搜索/投影时,如何重命名字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以重命名在查找查询中返回的字段的名称?我想使用类似$rename的名称,但是我不想更改正在访问的文档.我只想以不同的方式检索它们,就像SQL中的SELECT COORINATES AS COORDS一样.

Is it possible to rename the name of fields returned in a find query? I would like to use something like $rename, however I wouldn't like to change the documents I'm accessing. I want just to retrieve them differently, something that works like SELECT COORINATES AS COORDS in SQL.

我现在要做什么:

db.tweets.findOne({}, {'level1.level2.coordinates': 1, _id:0})
{'level1': {'level2': {'coordinates': [10, 20]}}}

我想返回的是: {'coords': [10, 20]}

推荐答案

所以基本上使用 .find() :

So basically using .aggregate() instead of .find():

db.tweets.aggregate([
    { "$project": {
        "_id": 0,
        "coords": "$level1.level2.coordinates"
    }}
])

这将为您提供所需的结果.

And that gives you the result that you want.

MongoDB 2.6及更高版本会像find一样返回游标".

MongoDB 2.6 and above versions return a "cursor" just like find does.

请参见 $project 以及其他聚合框架运算符以获取更多详细信息.

See $project and other aggregation framework operators for more details.

在大多数情况下,您只需要在处理游标时重命名从.find()返回的字段即可.以JavaScript为例,您可以使用 .map() 为此.

For most cases you should simply rename the fields as returned from .find() when processing the cursor. For JavaScript as an example, you can use .map() to do this.

从外壳:

db.tweets.find({},{'level1.level2.coordinates': 1, _id:0}).map( doc => {
  doc.coords = doc['level1']['level2'].coordinates;
  delete doc['level1'];
  return doc;
})

或更多内联:

db.tweets.find({},{'level1.level2.coordinates': 1, _id:0}).map( doc => 
  ({ coords: doc['level1']['level2'].coordinates })
)

这避免了服务器上的任何额外开销,并且应在以下情况下使用:额外的处理开销将超过实际减少的检索到的数据大小所获得的收益.在这种情况下(也是大多数情况),它将是最小的,因此最好重新处理游标结果以进行重组.

This avoids any additional overhead on the server and should be used in such cases where the additional processing overhead would outweigh the gain of actual reduction in size of the data retrieved. In this case ( and most ) it would be minimal and therefore better to re-process the cursor result to restructure.

这篇关于在MongoDB中执行搜索/投影时,如何重命名字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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