2

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

But it results in the following error:

MongoError: $arrayToObject requires an object keys of 'k' and 'v'. Found incorrect number of keys: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 Answer 1

2

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:

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

MongoDB playground

Sign up to request clarification or add additional context in comments.

5 Comments

I already tried this (see my post) the error I get is: MongoError: $arrayToObject requires an object keys of 'k' and 'v'. Found incorrect number of keys:1 And now: MongoError: $arrayToObject requires an array of key-value pairs, where the key must be of type string. Found key type: null
without the $ I get the desired output but without the field value as it results in an error. It seems like it's not possible to use $ inside arrayToObject. Also your MongoDB playground has no result?
So I suppose that $output evaluates to null for some reason. Either you have some missing parts in your data or your path is defined incorrectly. Could you modify your answer and paste what you're exactly trying to transform ? Or if you have multiple documents and some of that contain null values you can use docs.mongodb.com/manual/reference/operator/aggregation/ifNull to specify default value
@cxzzy you need dollar sign to refer to existing field, otherwise it's just a string, and it is allowed in $arrayToObject as you can see in Mongo playground example
Ah, that's it! Great! Thanks. I indeed had some empty values and setting a default value fixed the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.