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

查看:37
本文介绍了在 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]}

推荐答案

所以基本上使用 .aggregate() 而不是 .find():

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

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

这会给你想要的结果.

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天全站免登陆