Reputation: 350
I am trying to group the data that I get from mongoDB by repo Id my collection structure is:
{
"id":"8820624457",
"type":"CreateEvent",
"actor":{
"id":27394937,
"login":"Johnson0608",
"display_login":"Johnson0608",
"gravatar_id":"",
"url":"https://api.github.com/users/Johnson0608",
"avatar_url":"https://avatars.githubusercontent.com/u/27394937?"
},
"repo":{
"id":163744671,
"name":"Johnson0608/test",
"url":"https://api.github.com/repos/Johnson0608/test"
},
"payload":{
"ref":"master",
"ref_type":"branch",
"master_branch":"master",
"description":null,
"pusher_type":"user"
},
"public":true,
"created_at":"2019-01-01T15:00:00Z"
}
my code is :
collection.find({}).project({ 'repo.id': 1, 'actor.login': 1, 'type': 1 }).toArray(function (err, docs) {
assert.equal(err, null);
console.log("Found the following records");
res.status(200).json({ docs });
callback(docs);
});
I am trying to group by repo id but i don't know how(I am new to mongoDB)
Upvotes: 0
Views: 45
Reputation: 3387
Go to this MongoPlayAround
db.collection.aggregate([
{
$group: {
_id: "$repo.id",
Actors: {
$push: {
"login": "$actor.login"
}
}
}
}
])
Upvotes: 2
Reputation: 432
You can use the aggregation function.
Groups input documents by the specified _id expression and for each distinct grouping, outputs a document. The _id field of each output document contains the unique group by value.
collection
.find({})
.aggregate({
$group: {
_id : 'repo.id' // The thing you want to group by
// ... Other arguments
}
})
.project({'repo.id': 1, 'actor.login': 1, 'type': 1})
.toArray(function (err, docs) {
assert.equal(err, null);
console.log("Found the following records");
res.status(200).json({ docs });
callback(docs);
});
Upvotes: 0