MongoDB:从另一个集合推送相关数据

MongoDB: Push related data from another collection

本文关键字:数据 集合 另一个 MongoDB      更新时间:2023-09-26

我有一个由生成的报表数据组成的集合。

产品:

{
  location: 'Spain',
  month: 5,
  year: 2015,
  name: 'Cup',
  price: 100.32,
  type: 1
},
  ...

然后我有重要的数据:

报告:

{
  location: 'Spain',
  month: 5,
  year: 2015,
  stdPrice: 110.22,
  products : [] // Here is where I'd like to insert related data (location, month, year) 
//from Products
}

数据应该被存储回DB。

类似:

 products.forEach(function(product){
   report.forEach(function(data){
    if(product['location'] === data['location'] && product['month'] === data['month'] && product['year'] === data['year']){
       data['products'].push(product);
     }
   });
 });

有人知道怎么实现这个吗?我认为map-reduce是一个很好的方法。我也希望能够对猫鼬进行编程。

谢谢!

我可以自己完成这项工作。我没有在x操作后手动执行,因为我自己没有使它工作。

每组操作最多有1000个操作。如果一个组超过了这个限制,MongoDB会将该组划分为1000个或更小的组。例如,如果大容量操作列表包含2000个插入操作,MongoDB创建2个组,每个组有1000个操作。

来源
    var bulk = mongoose.model('Report').collection.initializeOrderedBulkOp();
    mongoose.model('Product').find({}).exec(function (error, doc) {
        doc.forEach(function (value, index) {
            if (index % 500 === 0) {
                console.log('Current index: ', index);
            }
            bulk.find({
                location: value._doc.location,
                month: {$lte: value._doc.month}
            }).updateOne({
                "$push": {
                    "products": {
                        "location": doc.location,
                        "month": doc.month,
                        "year": doc.year,
                        "name": doc.name,
                        "price": doc.price,
                        "type": doc.type
                    }
                }
            });
        });
        console.log('Bulk Executing');
        bulk.execute(function (err, results) {
            if (err)
                console.error(err);
            else
                console.log(results.toJSON());
        });
    });

感谢@yogesh提供的MongoDB代码

使用mongo批量操作如下:

 var bulk = db.report.initializeOrderedBulkOp(),
    count = 0;
 db.products.find().forEach(function(doc) {
    bulk.find({
        "location": doc.location,
        "month": doc.month
    }).updateOne({
        "$push": {
            "products": {
                "location": doc.location,
                "month": doc.month,
                "year": doc.year,
                "name": doc.name,
                "price": doc.price,
                "type": doc.type
            }
        }
    });
    count += 2;
    if(count % 500 == 0) {
        bulk.execute();
        bulk = db.report.initializeOrderedBulkOp();
    }
 });
 if(count % 500 !== 0) bulk.execute();

for ref check this