3

I have a Javascript Array filled with mean Values and I want to insert them into a collection with a field named "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. 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. I have 98 Documents and the Array has also a length of 98.

The Collection looks like this with the name "cmean":

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

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

}

and the Array:

[
    33.89923155012405, 
    5.063347068609219
]
4
  • lastedit?? what syntax is this ? use find in update? Commented Mar 15, 2018 at 12:40
  • @chridam answer is right , just missing } in line4 Commented Mar 15, 2018 at 12:44
  • 1
    Check the updated answer Commented Mar 15, 2018 at 13:25
  • 1
    @chridam Works perfectly. Thank you so much. :) Commented Mar 15, 2018 at 13:32

2 Answers 2

3

You can use the forEach method on the array to iterate it and update the collection. Use the index to get the _id to be used in the update query, something like the following:

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:

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Are all the _id's zero padded?
No after the zeroes there are names
0
update({"_id": id}, $set: {"mean": myArray}, function(res, err) { ... });

If you are using mongoose, you also have to change data model from string to array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.