0

I'm new in MongoDB and NodeJS. I want to do an aggregate from another collection using NodeJS.

The thing is I have collection name test1 There I have some field like rcptid, rcptdate, ammount etc.

Now I have to insert data another collection test2 rcptdate,totalamount sum of amount from test1 collection.

The SQL query like this:

Insert into teste(rcptdate, totalamount) values(Select 
     recptdate,Sum(amount) from test1 group by recptdate);

How can I make this in NodeJS? Please help Me thanks in Advance.

1 Answer 1

1

I would like to suggest to go through the MongoDB documentation.
For your specific problem check $group and aggregation

A. If your date is not biased with time then you can use below aggregation:

db.getCollection('tests').aggregate([{
  $group : {
    _id : "$rcptdate",
    "totalAmmount" : {
      "$sum" : "$ammount"
    }
  }
}]);

Output:

/* 1 */
{
    "_id" : ISODate("2018-10-24T00:00:00.000Z"),
    "totalAmmount" : 3
}

/* 2 */
{
    "_id" : ISODate("2018-10-23T10:00:00.000Z"),
    "totalAmmount" : 10
}

B. If you want date by day of the month then use below aggregation:

db.getCollection('tests').aggregate([{
  $group : {
    _id : { 
      "day" : {"$dayOfMonth" : "$rcptdate"}
    },
    "totalAmmount" : {
      "$sum" : "$ammount"
    }
  }
}])

Output:

/* 1 */
{
    "_id" : {
        "day" : 24
    },
    "totalAmmount" : 3
}

/* 2 */
{
    "_id" : {
        "day" : 23
    },
    "totalAmmount" : 16
}

And, how you can achieve in NodeJS using mongoose library.

let pipeline = [{
  $group : {
    _id : "$rcptdate",
   "totalAmmount" : {
     "$sum" : "$ammount"
   }
 }
}];

test1Model.aggregate(pipeline) // Get data from here
  .allowDiskUse(true)
  .exec(function(err, data) {
    if(err || !data || !data[0]){
      Logger.error("Error ");
    } else{
      let tempObj = data[0];
      var test2 = new Test2Model(tempObj);
      test2.save(function(error, data) { // Insert data to next DB
        callback(error, data);
      });
    }
  });
Sign up to request clarification or add additional context in comments.

3 Comments

Just an addition to your pipeline. To achieve the "insert data another collection" requirement, you could add an $out stage
Brother Where I put the url like "router.get('/acchead/particularname',function(req,res){ acchead.find({parent:10700000}).then(function(acchead){ res.send({"Acchead":acchead}); }) });" this is get mine will be put
Brother Where I put the url like "router.get('/acchead/particularname',function(req,res){ acchead.find({parent:10700000}).then(function(acchead){ res.send({"Acchead":acchead}); }) });" this is get mine will be post

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.