Search code examples
pythonmongodbpymongomongoengine

How can I transpose a list of documents in MongoDB?


I have a document like:

{
   "_id": "6345e01473144cec0073ea95",
   "results": [
        {"total_cost": 10, "total_time": 20},
        {"total_cost": 30, "total_time": 40}
   ]
}

And I want to 'transpose' the list of documents to get:

{
    "total_cost": [10, 30],
    "total_time": [20, 40]
}

How can I find an object by ID, and then apply a transform on a list of documents with a mongo aggregation?

Every question/answer I have seen doing this has been for multiple documents, however this is for a single document with a list field.

(I am using MongoEngine/Pymongo so I have included the python tag)


Solution

  • simply access the fields with dot notation. You can think the projection of the fields as an individual array, i.e. results.total_cost is an array with content [10, 30]

    db.collection.aggregate([
      {
        $project: {
          total_cost: "$results.total_cost",
          total_time: "$results.total_time"
        }
      }
    ])
    

    Here is the Mongo Playground with your reference.