Rifat Murtuza
Rifat Murtuza

Reputation: 119

Mongdb insert data in a collection from another collection using Node.js Api

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.

Upvotes: 0

Views: 152

Answers (1)

Hardik Shah
Hardik Shah

Reputation: 4220

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);
      });
    }
  });

Upvotes: 1

Related Questions