基本上是使用.aggregate()
而不是.find()
:
db.tweets.aggregate([
{ "$project": {
"_id": 0,
"coords": "$level1.level2.coordinates"
}}
])
这样就可以得到您想要的结果。
MongoDB 2.6及以上版本会像find一样返回一个“游标”。
更多详细信息请参见$project
和其他聚合框架运算符。
对于大多数情况,处理游标时应该只需重命名从.find()
返回的字段。以JavaScript为例,您可以使用.map()
来完成此操作。
从shell中:
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 })
)
这样可以避免服务器上的任何额外开销,并且应该在这种情况下使用,即额外处理开销会超过实际减小检索数据大小的收益。在这种情况下(以及大多数情况下),它将是最小的,因此更好地重新处理游标结果以进行重构。