1

I have a collection where every document has this kind of structure:

{
  docName: "Document Name",
  probabilities: [
            { topicName:"topic1", prob: 0.3  },
            { topicName:"topic2", prob: 0.4  }, 
            { topicName:"topic3", prob: 0.23 }
              ...
            ]
 otherField: data,
 ...
}

I need to trnaform them into something like this:

{
  docName: "Document Name",
  topic1: 0.3,
  topic2: 0.4, 
  topic3: 0.23,
  ...
  otherField: data,
  ...
}

I tried using $arrayToObject and $objectToArray but I didn't figure out how to make it work.

Thanks in advance for your help!

1 Answer 1

2

You can use below aggregation

db.collection.aggregate([
  { "$replaceRoot": {
    "newRoot": {
      "$mergeObjects": [
        "$$ROOT",
        { "$arrayToObject": {
          "$map": {
            "input": "$probabilities",
            "in": {
              "k": "$$this.topicName",
              "v": "$$this.prob"
            }
          }
        }}
      ]
    }
  }},
  { "$project": { "probabilities": 0 }}
])

MongoPlayground

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

Comments

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.