1

I have a collection in this format:

{
  "place":"land",
  "animal":"Tiger",
  "name":"xxx"
},
{
  "place":"land",
  "animal":"Lion",
  "name":"yyy"
}

I want to result to be something like this:

{
  "place":"land".
  "animals":{"Lion":"yyy", "Tiger":"xxx"}
}

I wrote the below query. I think there needs to be another group stage but not able to write it.

db.collection.aggregate({
  '$group': {
  '_id':{'place':'$place', 'animal':'$animal'},
  'animalNames': {'$addToSet':'$name'}
  }
})

What changes need to be made to get the required result?

2 Answers 2

2
  1. $group - Group by animals. Push objects with { k: "animal", v: "name" } type into animals array.
  2. $project - Decorate output document. Convert animals array to key-value pair via $arrayToObject.
db.collection.aggregate([
  {
    "$group": {
      "_id": "$place",
      "animals": {
        "$push": {
          k: "$animal",
          v: "$name"
        }
      }
    }
  },
  {
    $project: {
      _id: 0,
      place: "$_id",
      animals: {
        "$arrayToObject": "$animals"
      }
    }
  }
])

Sample Mongo Playground

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

Comments

0

If you are on version >=4.4, a reasonable alternative is to use the $function operator:

db.foo.aggregate([
    {$project: {
        'income_statement.annual': {
            $function: {
                body: function(arr) {                      
                    return arr.sort().reverse();
                },
                args: [ "$income_statement.annual" ],
                lang: "js"
            }}
    }}
]);

1 Comment

Animals need lots of help determining their annual income. 8-)

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.