【问题标题】:How do I rename fields in the outputs of a Mongo query? [duplicate]如何重命名 Mongo 查询输出中的字段? [复制]
【发布时间】:2017-06-01 21:37:39
【问题描述】:

我想在 MongoDB 的 mongoose 函数中转换这个 SQL 查询(我的目标是将描述转换为 desc)。

select description as desc from book

如何修复此功能?

book.find({})
    .lean()
    .exec(function(err, recs) {
       if (err) {
           console.warn(err)
       } else {
           console.log(recs);
     });

【问题讨论】:

  • db.book.aggregate([ { "$project": { "_id": 0, "desc": "$description" }} ])

标签: mongodb mongoose mongodb-query


【解决方案1】:

您可以尝试在aggregation pipeline 中进行投影

book.aggregate([
    {
        $project: {
            _id: 0,  
            'desc': '$description' //aliasing 
        }
    }
], function (err, recs) {
    if (err) {
        console.log(err);
    } else {
        console.log(recs);
    }
});

here阅读更多关于aggregation的信息

【讨论】:

  • 它有效,谢谢。我在哪里放置 'where' ({_id: 0}) 对象?以及如何重命名记录中的对象属性?例如{_id: 0, title: 'Hello world', author: {name: 'John', surname: 'Cena'}} 我想将 author.name 重命名为 name。
  • {_id: 0, title: 'Hello world', author: {name: 'John', surname: 'Cena', nationality: 273}} 我还想提取 author.nationality.name 作为国籍,它是另一个集合中记录的 ID。
  • 对于author.name,您可以在$project 字段中写入name: '$author.name'
  • 国籍呢?如何提取字段“姓名”并将其重命名为“国籍”?
  • $project 中与nationality: $author.nationality.name 相同
猜你喜欢
  • 2013-01-05
  • 2018-10-01
  • 1970-01-01
  • 2013-08-11
  • 2013-05-30
  • 1970-01-01
  • 2019-03-08
  • 1970-01-01
  • 2020-03-22
相关资源
最近更新 更多