简体   繁体   English

将多个文档上传到mongoDB

[英]Upsert multiple documents into mongoDB

I have a array of values, some of the values in the array may already be present in my database. 我有值的阵列 ,一些数组中的值可能已经存在于我的数据库。 I want to upsert the new values and increase the count of the old values. 我想upsert新的价值观和增加老值的计数 One way to do this is : 一种方法是:

  • For all the values that are present in the database use a update command and increment count. 对于数据库中存在的所有值,请使用更新命令和增量计数。 It can be done using : db.test.update({ link: {$in: ["A", "B"]}}, {$inc: {count: 1}}, {upsert: true, multi:true}) 可以使用: db.test.update({ link: {$in: ["A", "B"]}}, {$inc: {count: 1}}, {upsert: true, multi:true})

  • For all the values not present in my database, check each and every value and upsert it into the database. 对于数据库中不存在的所有值,请检查每个值,然后将其向上插入数据库。

The second step may put some load on the network. 第二步可能会给网络带来一些负担。 Is there any way to do the second step in one command? 有什么方法可以在一个命令中执行第二步吗?

For example consider this : 例如考虑一下

Initial state of my database : 我的数据库的初始状态

{ "_id" : ObjectId("5a45f97f84527190e1f28cb7"), "link" : "A", "count" : 3 } 

and I have the array as following: const values = ['A', 'B', 'C'] 并且我有如下数组: const values = ['A', 'B', 'C']

Now I want to have something like this: 现在我想要这样的东西:

{"_id": ObjectId("abc"), "link": "A", "count" : 4},
{"_id": ObjectId("xyz"), "link": "B", "count" : 1},
{"_id": ObjectId("fgh"), "link": "C", "count" : 1}

To achieve the second step (as you mentioned) optimally you can perform lookup in your DB using find() method. 为了最佳地完成第二步(如您所述),您可以使用find()方法在DB执行查找。

If the array value isn't present in the DB , then find() is gonna return an empty object. 如果DB没有数组值,则find()将返回一个空对象。 So you just see the length of the object returned from find() . 因此,您只看到find()返回的对象的长度。 If found empty, insert into DB else update the info. 如果发现为空,则插入DB否则更新信息。

Example code for nodejs environment: nodejs环境的示例代码:

var db = mongojs('dbname', ['collection_name']);

var theLink = 'XYZ';

db.collection_name.find({link: theLink}, function (err, obj) {
    if (err)
        throw err;
    if (obj.length == 0)
        // write logic to insert
    else
        // write logic to update
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM