【问题标题】:how to get alias name on fetching the data from mongoDB using find query如何使用查找查询从 mongoDB 获取数据时获取别名
【发布时间】:2017-12-13 09:00:19
【问题描述】:

我正在使用 MongoDB,我的表(表名“My_Table”)看起来像

attributes: {
        user_id: {
            type: 'string'
        }}

我喜欢将字段名称user_id 作为user 作为别名

我能够使用查找查询 My_Table.find({}).then(function(data){console.log(data)}) 获取 My_Table 的值 使用这个查询我可以得到{user_id: "11111"}的输出 但我的预期输出别名为{user : "11111"}

为此我不知道是否需要在属性中添加一些字段或需要更改我的查找方法。

请大家帮忙解决一下这个问题,先谢谢了

【问题讨论】:

    标签: javascript node.js mongodb mongodb-query sails.js


    【解决方案1】:
    My_Table.aggregate([
    {$match:{}},
    {$project:{user:"$user_id",id:1}}
    ])
    

    在 $project 或 $addFields 阶段,您可以随意格式化输出

    【讨论】:

    • 您的代码可能是正确的,但也请添加一些解释。
    • 我的 JSON 格式为 [{user_id: 123, id : 01 }, {user_id : 456, id: 02}]。当我使用此代码 My_Table.aggregate([ {$match:{}}, {$project:{_id:0, id:"$attributes.user_id"}} ]) 它给出的空响应为 [ {}, { } ]
    • 我已经更新了我的答案,但你已经在文档中有 id 字段?
    • 对不起,我可以得到user_id作为用户,现在也不可能
    猜你喜欢
    • 2021-05-09
    • 2017-04-09
    • 2019-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多