简体   繁体   English

将Javascript数组值放入Mongodb集合值

[英]Put Javascript Array Values into Mongodb Collection Values

I have a Javascript Array filled with mean Values and I want to insert them into a collection with a field named "mean". 我有一个填充了均值的Javascript数组,我想将它们插入到一个名为“mean”的字段的集合中。 The Field "mean" already exists and has already values in them and now I want to update them with the values of the Array. 字段“mean”已经存在并且已经存在值,现在我想用Array的值更新它们。 To be more specific: I want the first Value of the Array to be in the first Document under the field "mean" and so on. 更具体一点:我希望数组的第一个值位于“mean”字段下的第一个Document中,依此类推。 I have 98 Documents and the Array has also a length of 98. 我有98个文件,数组的长度也是98。

The Collection looks like this with the name "cmean": 该集合的名称如此“cmean”:

{ 
    "_id" : "000", 
    "mean" : 33.825645389680915

}
{ 
    "_id" : "001", 
    "mean" : 5.046005719077798 

}

and the Array: 和数组:

[
    33.89923155012405, 
    5.063347068609219
]

You can use the forEach method on the array to iterate it and update the collection. 您可以在数组上使用forEach方法来迭代它并更新集合。 Use the index to get the _id to be used in the update query, something like the following: 使用索引获取要在更新查询中使用的_id ,如下所示:

meansArray.forEach(function(mean, idx) {
    var id = db.cmean.find({}).skip(idx).limit(1).toArray()[0]["_id"];
    db.cmean.updateOne(
        { "_id": id },
        { "$set": { "mean": mean } },
        { "upsert": true }
    );
});

For large collections, you can streamline your db performance using bulkWrite as follows: 对于大型集合,您可以使用bulkWrite简化数据库性能,如下所示:

var ops = [];

meansArray.forEach(function(mean, idx) {
    var id = db.cmean.find({}).skip(idx).limit(1).toArray()[0]["_id"];
    ops.push({
        "updateOne": {
            "filter": { "_id": id },
            "update": { "$set": { "mean": mean } },
            "upsert": true            
        }
    });

    if (ops.length === 1000 ) {
        db.cmean.bulkWrite(ops);
        ops = [];
    }
})

if (ops.length > 0)
    db.cmean.bulkWrite(ops);
update({"_id": id}, $set: {"mean": myArray}, function(res, err) { ... });

如果您使用的是mongoose,则还必须将数据模型从字符串更改为数组。

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

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