How can I use a cursor.forEach() in MongoDB using Node.js?

前端 未结 10 853
你的背包
你的背包 2020-11-27 14:04

I have a huge collection of documents in my DB and I\'m wondering how can I run through all the documents and update them, each document with a different value.

10条回答
  •  悲哀的现实
    2020-11-27 14:43

    let's assume that we have the below MongoDB data in place.

    Database name: users
    Collection name: jobs
    ===========================
    Documents
    { "_id" : ObjectId("1"), "job" : "Security", "name" : "Jack", "age" : 35 }
    { "_id" : ObjectId("2"), "job" : "Development", "name" : "Tito" }
    { "_id" : ObjectId("3"), "job" : "Design", "name" : "Ben", "age" : 45}
    { "_id" : ObjectId("4"), "job" : "Programming", "name" : "John", "age" : 25 }
    { "_id" : ObjectId("5"), "job" : "IT", "name" : "ricko", "age" : 45 }
    ==========================
    

    This code:

    var MongoClient = require('mongodb').MongoClient;
    var dbURL = 'mongodb://localhost/users';
    
    MongoClient.connect(dbURL, (err, db) => {
        if (err) {
            throw err;
        } else {
            console.log('Connection successful');
            var dataBase = db.db();
            // loop forEach
            dataBase.collection('jobs').find().forEach(function(myDoc){
            console.log('There is a job called :'+ myDoc.job +'in Database')})
    });
    

提交回复
热议问题