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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.