0

I have a dataset of 1700 entries which have entries like this:

{
    "_id" : ObjectId("5a7acda13b808dbed05d6505"),
    "name" : "Nil",
    "symbol" : "@A",
    "isin" : "47",
    "group" : "Nil",
    "sector" : "Nil",
    "tagcounter" : 0
},
{
    "_id" : ObjectId("5a7acda13b808dbed05d6506"),
    "name" : "Nil",
    "symbol" : "@B",
    "isin" : "48",
    "group" : "Nil",
    "sector" : "Nil",
    "tagcounter" : 0
},
{
    "_id" : ObjectId("5a7acda13b808dbed05d6507"),
    "name" : "Nil",
    "symbol" : "@C",
    "isin" : "49",
    "group" : "Nil",
    "sector" : "Nil",
    "tagcounter" : 0
}//.....upto 1700 entries

Now I have an array which has some value like this:

var array = ['Fruit', 'Vegetable', 'Drinks', 'Fast-Food', 'Healthy-Food'];

Now I want to update entire sector values from "Nil" to "Any value From array". The expected result will be like this:

{
    "_id" : ObjectId("5a7acda13b808dbed05d6505"),
    "name" : "Nil",
    "symbol" : "@A",
    "isin" : "47",
    "group" : "Nil",
    "sector" : "Fruit",
    "tagcounter" : 0
},
{
    "_id" : ObjectId("5a7acda13b808dbed05d6506"),
    "name" : "Nil",
    "symbol" : "@B",
    "isin" : "48",
    "group" : "Nil",
    "sector" : "Drinks",
    "tagcounter" : 0
},
{
    "_id" : ObjectId("5a7acda13b808dbed05d6507"),
    "name" : "Nil",
    "symbol" : "@C",
    "isin" : "49",
    "group" : "Nil",
    "sector" : "Fast-Food",
    "tagcounter" : 0
}

What I did for this is:

db.Collection.update({},{$set: {'sector': ['Fruit', 'Vegetable', 'Drinks', 'Fast-Food', 'Healthy-Food']}}, {multi: true }, function(error, data){
  if( error) {
    console.log(error);
  } else {
    console.log(data);
  }
});

But by this, The Entire Array is copied on every field rather than one value.

I know there is a problem on providing the whole array.

If anyone has solution for this then please let me know.

1 Answer 1

1
db.Collection.find({}).forEach((doc) => {
  db.Collection.update({_id: doc._id}, {$set: {sector: array[Math.floor(Math.random()* array.length)]}})
})

Refer here for forEach cursor documentation.

Sign up to request clarification or add additional context in comments.

2 Comments

Generates Error i.e db.Collection.find().forEach is not a function
added link to the forEach cursor documentation

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.