简体   繁体   English

更新集合中元素的随机数组值

[英]Update random array value of elements on the collection

I have a dataset of 1700 entries which have entries like this: 我有1700个条目的数据集,这些条目具有以下内容:

{
    "_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". 现在,我想将整个扇区值从“ Nil”更新为“ 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. 有关forEach游标的文档,请参见此处

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

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