How to use the aggregate function in a meteor

I am 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 follows

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

when iam using the following command in mongo shell gives 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 the same in my meteorite application aggregate doesnโ€™t work ...... so I can do the same with the find or findOne methods ............. or if there is any possibility to use the aggregate function in my meteorite application ....

+8
source share
4 answers

I used the meteorhacks package: aggregate. It only works 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/

+5
source

Here is what I tried manually and worked for me:

 var rawUsers = Meteor.users.rawCollection(); var aggregateQuery = Meteor.wrapAsync(rawUsers.aggregate, rawUsers); var pipeline = [ {$match: {}}, {$project: {username: 1, profile: 1}} ]; var result = aggregateQuery(pipeline); return result; 

Read more about Meteor.wrapAsync here

+3
source

You need to add the package to open the aggregate function:

meteor add monbro:mongodb-mapreduce-aggregation

Then you can use the code as usual:

 var MyCollection = new Mongo.Collection('metrics'); var pipeline = [ {$group: {_id: null, resTime: {$sum: "$resTime"}}} ]; var result = MyCollection.aggregate(pipeline); 

Just a few notes, this works best on the server side. In order for documents to be able to use it on the client side, a package plug is needed, check the package documents: https://atmospherejs.com/monbro/mongodb-mapreduce-aggregation

0
source

Using rawCollection , you can pass the same pipeline that you used in your Mongo shell.

You do not need to install a third-party package for this.

 const stats = await MyCollection.rawCollection() .aggregate([ {$match: {_id: 12}}, {$unwind: "$People"}, {$unwind: "$People.person"}, {$match: {"People.uuid": "123", "People.person.uuid" : "add32"}} ]) .toArray(); 
0
source

Source: https://habr.com/ru/post/982243/


All Articles