1

Using a MongoDB aggregate query, how do I convert an array of documents to a single document. The array can have N number of documents.

Before

{
    "_id": "10217941",
    "data": [
    {
        "count": 2,
        "score": "0.5"
    },
    {
        "count": 6,
        "score": "0.3"
    },
    {
        "count": 5,
        "score": "0.8"
    }
    ]
}

After

"_id": "10217941",
"0.3": 6,
"0.5": 2,
"0.8": 5
1

1 Answer 1

1

Try this:

db.collection.aggregate([
    {
        "$addFields": {
            "data": {
                "$arrayToObject": {
                    "$map": {
                        "input": "$data",
                        "as": "item",
                        "in": {
                            "k": "$$item.score",
                            "v": "$$item.count"
                        }
                    }
                }
            }
        }
    },
    {
        "$addFields": {
            "data._id": "$_id"
        }
    },
    {
        "$replaceRoot": {
            "newRoot": "$data"
        }
    }
]);
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.