简体   繁体   English

在 MongoDB 中插入带有随机数据的文档

[英]Insert documents with random data in MongoDB

Goog morning.早上好。

I am trying to code some scripts to insert documents in a collection in MongoDB.我正在尝试编写一些脚本以在 MongoDB 的集合中插入文档。 The problem is that I need the data to be random.问题是我需要数据是随机的。 This is my code:这是我的代码:

async function run(service) {
  try {
    await client.connect();
    const database = client.db("myDb");
    const collection = database.collection("myEvents");
    // create a filter to update all movies filtering the service
    const filter = { service: service };
    const updateDoc = {
        $set: {
          idIn: (Math.floor(Math.random() * 20) + 1) + 5, 
          idOut: Math.floor(Math.random() * 10) + 1
        },
    };

    const result = await collection.updateMany(filter, updateDoc);
  } finally {
    await client.close();
  }
}
let service = readline.question("Insert an id: ");
run(service).catch(console.dir); 

Here the data is created once and then updates all the documents in the collection with the same values.这里数据被创建一次,然后使用相同的值更新集合中的所有文档。 I need to update every document with two different (IdIn and IdOut) values.我需要用两个不同的(IdIn 和 IdOut)值更新每个文档。

Thanks in advance.提前致谢。

The problem here is how a random number is generated.这里的问题是如何生成随机数。 If all numbers are based in the same seed, all will be the same.如果所有数字都基于同一个种子,则所有数字都相同。

So you haveto use forEach() to iterate over the collection and adding values, then, the seed is not the same for all values.因此,您必须使用forEach()迭代集合并添加值,然后,所有值的种子都不相同。

Note that forEach is not the same using mongoose and mongo .请注意,使用mongoosemongo forEach并不相同。 Using mongo you can do collection.find().forEach(...) .使用mongo你可以做collection.find().forEach(...)

Using mongoose is in this way:使用mongoose是这样的:

model.find({}).then(doc => 
  doc.forEach(element => {
    element.idIn = (Math.floor(Math.random() * 20) + 1) + 5
    element.idOut = Math.floor(Math.random() * 10) + 1
    element.save()
  }))

The find query is empty because you want to update every document. find查询是空的,因为您要更新每个文档。 With the values returned by the query (all documents), you can iterate one by one using forEach , and calculate a random number for each one and adding to value.使用查询返回的值(所有文档),您可以使用forEach一一迭代,并为每个计算一个随机数并添加到 value。
And after that save the document into collection.然后将文档保存到集合中。

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

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