簡體   English   中英

更新集合中元素的隨機數組值

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

我有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

現在,我有一個數組,其值如下所示:

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

現在,我想將整個扇區值從“ Nil”更新為“ Any value From array”。 預期的結果將是這樣的:

{
    "_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
}

我為此所做的是:

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);
  }
});

但是,這樣,整個數組將復制到每個字段而不是一個值。

我知道在提供整個陣列方面存在問題。

如果有人對此有解決方案,請告訴我。

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

有關forEach游標的文檔,請參見此處

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM