是否可以重命名在查找查询中返回的字段的名称?我想使用像 $rename 这样的东西,但是我不想更改我正在访问的文档。我只想以不同的方式检索它们,就像SQL中的 SELECT COORINATES AS COORDS 一样。
$rename
SELECT COORINATES AS COORDS
我现在要做的是:
db.tweets.findOne({}, {'level1.level2.coordinates': 1, _id:0}) {'level1': {'level2': {'coordinates': [10, 20]}}}
我希望返回的是: {'coords': [10, 20]}
{'coords': [10, 20]}
上云精选
2核2G云服务器 每月9.33元起,个人开发者专属3年机 低至2.3折
正如@Neil Lunn所提到的,这可以通过聚合管道来实现:
从 Mongo 4.2 开始,可以使用 $replaceWith 聚合运算符将子文档替换为文档:
Mongo 4.2
$replaceWith
// { level1: { level2: { coordinates: [10, 20] }, b: 4 }, a: 3 } db.collection.aggregate( { $replaceWith: { coords: "$level1.level2.coordinates" } } // { "coords" : [ 10, 20 ] }
由于您提到了 findOne ,因此您还可以将结果文档的数量限制为1:
findOne
db.collection.aggregate([ { $replaceWith: { coords: "$level1.level2.coordinates" } }, { $limit: 1 } ])
在 Mongo 4.2 和启动 Mongo 3.4 之前,可以使用 $replaceRoot 代替 $replaceWith
Mongo 3.4
$replaceRoot
db.collection.aggregate( { $replaceRoot: { newRoot: { coords: "$level1.level2.coordinates" } } } )
正如我们所知道的,通常,$project阶段采用字段名称并指定1或0/true或false以在输出中包含字段,我们还可以针对字段指定值而不是true或false来重命名字段。以下是语法
db.test_collection.aggregate([ {$group: { _id: '$field_to_group', totalCount: {$sum: 1}