Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use aggregate function in meteor

Tags:

mongodb

meteor

I'm working on the following document

{
"_id" : 12,
"firstName" : "wer",
"People" : [ 
    {
        "uuid" : "123",
        "name" : "sugun",
        "person" : [ 
            {
                "uuid" : "add32",
                "name" : "ssss"
            }, 
            {
                "uuid" : "fdg456",
                "name" : "gfg"
            }
        ]
    }, 
    {
        "uuid" : "222",
        "name" : "kiran"
    }
]
} 

I want to get my output as following

{
"_id" : 456,
"People" : [ 
    {
        "uuid" : "123",
        "name" : "sugun",
        "person" : [ 
            {
                "uuid" : "add32",
                "name" : "ssss"
            }
        ]
    }
]
}

when iam using following command in mongo shell it give my required output

 db.people.aggregate([
    {$match: {_id: 12}}, 
    {$unwind: "$People"}, 
    {$unwind: "$People.person"}, 
    {$match: {"People.uuid": "123", "People.person.uuid" : "add32"}}
 ])

but when iam using same in my meteor app aggregate is not working...... so can i do the same using find or findOne methods............. or if there is any possibility to use aggregate function in my meteor app....

like image 771
Gopal Rao Avatar asked Feb 10 '15 06:02

Gopal Rao


2 Answers

By using rawCollection you can pass in the same pipeline that you've been using in your mongo shell.

There is no need to install a third-party package to do this.

const stats = await MyCollection.rawCollection()
    .aggregate([
      {$match: {_id: 12}}, 
      {$unwind: "$People"}, 
      {$unwind: "$People.person"}, 
      {$match: {"People.uuid": "123", "People.person.uuid" : "add32"}}
    ])
    .toArray();
like image 109
ninjaPixel Avatar answered Oct 25 '22 09:10

ninjaPixel


I used the meteorhacks:aggregate package. It works only on the server side.

meteor add meteorhacks:aggregate

MyCollection.aggregate({ 
  $match: { 
    propertyToQuery: 'valueForProperty' 
  }, { 
    $group: {
      _id: '$propertyToGroupBy',
      result: { $operation: '$propertyToPerformOperationOn' }
    }
});

https://github.com/meteorhacks/meteor-aggregate https://themeteorchef.com/snippets/aggregations-in-mongodb/

like image 25
Dmitry Krychylskyy Avatar answered Oct 25 '22 07:10

Dmitry Krychylskyy