简体   繁体   English

如何创建自定义对象作为输出,字段名称作为 MongoDB 中的键?

[英]How to create a custom object as output with field name as key in MongoDB?

Changing the output of an aggregation query where the key is the field name from the database.更改聚合查询的输出,其中键是数据库中的字段名称。

I tried the following: How to use field value as key name in Mongodb result我尝试了以下操作: How to use field value as key name in Mongodb result

But it results in the following error:但它导致以下错误:

MongoError: $arrayToObject requires an object keys of 'k' and 'v'. MongoError: $arrayToObject 需要 'k' 和 'v' 的对象键。 Found incorrect number of keys:1发现不正确的键数:1

var data = await Message.aggregate([
    {
      $group: {
        _id: '$message',
        last_message: { $last: '$date_create', },
        conversation: {
          $push: '$$ROOT',
        },
      },
    },
    {
      $project: {
        input: { $arrayElemAt: ['$conversation.message', 0] },
        output: { $arrayElemAt: ['$conversation.mainTopic', 0] },
        _id: 0,
      },
    },
    { $sort: { last_message: -1 } },
  ]);

I want to change the ouput from (current result):我想从(当前结果)更改输出:

{ "input": "Test", "output": "general" }, {“输入”:“测试”,“输出”:“一般”},

TO:到:

{ "input": "Test", "output": { general: 1, }, }, {“输入”:“测试”,“输出”:{一般:1,},},

To convert { "input": "Test", "output": "general" } into { "input": "Test", "output": { general: 1 } } you need $arrayToObject operator which takes either an array of objects with k and v fields or an array of 2-element arrays like below:要将{ "input": "Test", "output": "general" }转换为{ "input": "Test", "output": { general: 1 } }你需要$arrayToObject运算符,它接受一个数组具有kv字段或 2 元素数组的数组,如下所示:

db.collection.aggregate([
    {
        $project: {
            _id: 0,
            input: 1,
            output: {
                $arrayToObject: [
                    [
                        [ "$output", 1 ]
                    ]
                ]
            }
        }
    }
])

MongoDB playground MongoDB 游乐场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM