I am new to mongodb aggregation. Let's say I have this data:
[
{
"end_year": 2020,
"intensity": 12,
"sector": "Information Technology",
"topic": "robot",
"insight": "62 market research reports study robotics industry",
"url": "http://robohub.org/62-market-research-reports-study-robotics-industry/",
"region": "",
"start_year": 2016,
"impact": "",
"added": "July, 16 2016 02:44:49",
"published": "July, 11 2016 00:00:00",
"country": "",
"relevance": 3,
"pestle": "Economic",
"source": "Robothub",
"title": "Forecasts the industrial robotics market in APAC to grow at a CAGR of 8.7% during the period 2016-2020 in the top 5 segments.",
"likelihood": 4
},
{
"end_year": "",
"intensity": 2,
"sector": "Government",
"topic": "government",
"insight": "Oil, Greed, and Grievances in the Middle East and North Africa",
"url": "https://www.newsecuritybeat.org/2016/07/oil-greed-grievances-middle-east-north-africa/",
"region": "",
"start_year": "",
"impact": "",
"added": "July, 16 2016 01:12:21",
"published": "July, 12 2016 00:00:00",
"country": "",
"relevance": 1,
"pestle": "Political",
"source": "New Security Beat",
"title": "Countries threatened by larger-scale insurgencies might want to consider giving regional groups some share in central government decision-making.",
"likelihood": 2
}
]
This is my query:
// return all the countries associated with a single topic
const data = await Data.aggregate([
{ $match: {} },
{ $group: { _id: "$topic",country: ["$country"],likelihood: ["$likelihood"],relevance: ["$relevance"],intensity: ["$intensity"] } }
])
I want to return all countries,likelihoods,relevances associated with a single/common topic
I know how to get the first and last ones using $first and $last operators. How do I get all of them in an array?
We can use $push operator to add all of the field values:
const data = await Data.aggregate([
{ $match: {} },
{ $group: { _id: "$topic",data: { $push: { country: "$country",likelihood: "$likelihood",relevance: "$relevance",intensity: "$intensity" } } } }
])