【问题标题】:Mongdb insert data in a collection from another collection using Node.js ApiMongodb 使用 Node.js Api 在另一个集合中插入数据
【发布时间】:2018-10-23 04:34:02
【问题描述】:

我是 MongoDB 和 NodeJS 的新手。我想使用 NodeJS 从另一个集合中进行聚合。

问题是我有集合名称 test1 那里我有一些字段,如 rcptid, rcptdate, ammount 等。

现在我必须从test1 集合中插入另一个集合test2 rcptdate,totalamount 的总和。

这样的 SQL 查询:

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

我怎样才能在 NodeJS 中做到这一点?请帮助我提前谢谢。

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    我想建议通过MongoDB documentation
    对于您的具体问题,请检查 $groupaggregation

    A. 如果您的日期不随时间变化,那么您可以使用以下聚合:

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

    输出:

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

    B.如果您想要day of the month 的日期,请使用以下聚合:

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

    输出:

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

    以及,如何使用mongoose 库在 NodeJS 中实现。

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

    【讨论】:

    • 只是对您的管道的补充。要实现“将数据插入另一个集合”的要求,您可以添加一个 $out 阶段
    • 兄弟 我在哪里放像 "router.get('/acchead/particularname',function(req,res){ acchead.find({parent:10700000}).then(function(acchead ){ res.send({"Acchead":acchead}); }) });"这是得到我的将被放
    • 兄弟 我在哪里放像 "router.get('/acchead/particularname',function(req,res){ acchead.find({parent:10700000}).then(function(acchead ){ res.send({"Acchead":acchead}); }) });"这是我的将发布
    猜你喜欢
    • 1970-01-01
    • 2015-09-25
    • 2016-09-22
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 2019-11-22
    • 2015-09-14
    • 2022-01-04
    相关资源
    最近更新 更多