在Mongoose上显示带有参数的对象列表

I have a find query that returns me a list of objects: { "_id": "5fb94fda487b9348c4291450", "name": [ { "NewConfirmed": 642686, "TotalConfirmed": 49315431, "NewDeaths": 9555, "TotalDeaths": 1242785, "NewRecovered": 288131, "TotalRecovered": 32473892 }, { "NewConfirmed": 116262, "TotalConfirmed": 6014461, "NewDeaths": 4640, "TotalDeaths": 371913, "NewRecovered": 77575, "TotalRecovered": 2492884 }, { ... Its all fine but I'm trying to make a new query with a status parameter with the value NewConfirmed or TotalConfirmed or NewDeaths to display only that specific field. So the endpoints would look like /something/status/:status. I already tried an aggregation with filter and a simple find but still havent figured nothing out. Anyone has any idea?


First of all, you need a query with this estructure: db.collection.aggregate([ { /**Your match object*/ }, { "$project": { "YourStatus": { "$first": "$name.YourStatus" } } } ]) Example here. Using mongoose you need to create the object query in this way: var query = {} query[status] = {"$first": "$name."+status} And do the mongoose query replacing the object by query object. var aggregate = await model.aggregate([ { //Your $match stage here }, { "$project": query } ]) Also, I've tested in local but my mongo version (I think) doesn't recognize $first so I've used $arrayElemAt. According to mongo docs is the same as $first. var status = "NewConfirmed" var query = {} query[status] = { $arrayElemAt: ["$name."+status, 0]} Also you can add _id: 0 into $project aggregate to not return this field. var query = {_id:0} //Here add _id: 0 to project object query[status] = { $arrayElemAt: ["$name."+status, 0]} //And the rest of the stage