Home > database >  MongoDB script data update
MongoDB script data update

Time:06-29

Is it possible to use a script to update the data in MongoDB? I'd like to run update queries but I don't want to (or can't) access the mongo shell. CSV files include my data. I utilize Hadoop to analyze data (extraction and transformation). I need to update some properties and retrieve the data back into MongoDB. I want to use the generated id as a reference for the change.

CodePudding user response:

yes, it is possible, you can write a script in Node Js for example and run it.

A simple line like: Users.updateMany({}, { $set: { name: 'New name' } }); Would update the field name in the users' collection with New name

Just put the update code inside a function and call that function.

CodePudding user response:

        const Course=require("../models/course.model");
        const addCourse= async(ctx)=>{
        console.log(ctx.request.body);
        const {courseName,coursefees,students}=ctx.request.body;
        try{ 
        const course=await Course.create({
        courseName:courseName,
        coursefees:coursefees,
        students:students
        });
        return (ctx.body = course);
        }catch(error){
        return (ctx.body={message:error.message}) 
        }
        }
        const getcourses=async(ctx)=>{
        try{
        const course=await Course.find().populate({
        path: "students",
        select: "name nic age",
        });
        return (ctx.body=course);
        }catch (error){
        return (ctx.body={message:error.message}) 
        }
        }
        const updateCourse = async(ctx)=>{
        try{
        const courseId =ctx.params.courseId;
        const {courseName,coursefees,students}=ctx.request.body;
        const course=await Course.findByIdAndUpdate(courseId,{
        courseName :courseName,
        coursefees :coursefees,
        students : students})
        return (ctx.body= course);
        }catch(error){
        return(ctx.body={message:error.message}) 
        }
        }
        const deletecourse=async(ctx)=>{
        try{
        const courseId=ctx.params.courseId;
        const course=await Course.findByIdAndDelete(courseId);
        return (ctx.body=course);
        }catch(error){
        return(ctx.body={message:error.message}) 
        }
        }
        const getCourseById=async(ctx)=>{
        try{
        const courseId=ctx.params.courseId;
        const course=await Course.findById(courseId);
        return (ctx.body=course);
        }catch(error){
        return(ctx.body={message:error.message}) 
        }
        }
        
    
    
    
    
    
    
    
    
    
    
    
        
        
    
        const Student=require("../models/students.model");
        const Course=require("../models/course.model");
        const addStudents= async(ctx)=>{
        console.log(ctx.request.body);
        const {name,nic,age,courseId}=ctx.request.body;
        try{ 
        const student=await Student.create({
        name: name,
        nic:nic,
        age: age,
        courseId:courseId
        });
        await Course.findByIdAndUpdate(courseId,{$push:{students:student._id}})
        return (ctx.body = student);
        }catch(error){
        return (ctx.body={message:error.message}) 
        }
        }
        const getStudent=async(ctx)=>{
        try{
        const student=await Student.find().populate({
        path: "courseId",
        select: "courseName coursefees",
        });
        return (ctx.body=student);
        }catch (error){
        return (ctx.body={message:error.message}) 
        }
        }
        module.exports={addStudents,getStudent}
    
    
    
    
    
    
        const mongoose=require('mongoose');
        const courseSchema=new mongoose.Schema({
        courseName:{type:String, required:true},
        coursefees:{type:Number, required:true},
        students:[{type:mongoose.Schema.Types.ObjectId, required:false
        ,ref:"students"}]
        })
        const Course=mongoose.model("course",courseSchema);
        module.exports=Course;
    
    
    
    
    
    
    
    
        const mongoose=require('mongoose');
        const studentSchema=new mongoose.Schema({
        name:{type:String, required:true},
        nic:{type:String, required:true},
        age:{type:Number, required:true},
        courseId:{type:mongoose.Schema.Types.ObjectId, required:false ,ref:"course"}
        })
        const Students=mongoose.model("students",studentSchema);
        module.exports=Students;








        const KoaRouter =require('koa-router');
        const { addCourse, getcourses, updateCourse, deletecourse, getCourseById } = 
        require('../controller/course.controller');
        const router =new KoaRouter({
        prefix:"/course"
        })
        router.post("/add",addCourse);
        router.get("/",getcourses);
        router.get("/:courseId",getCourseById);
        router.put("/:courseId",updateCourse);
        router.delete("/:courseId",deletecourse);
        module.exports=router;
        
        
    
    
    
    
    
    
    
        const KoaRouter =require('koa-router');
        const { addStudents, getStudent } = require('../controller/student.controller');
        const router =new KoaRouter({
        prefix:"/student"
        })
        router.post("/add",addStudents);
        router.get("/",getStudent);
        module.exports=router;
        
    
    
    
    
    
        
        const mongoose= require('mongoose');
        const dbconnect=()=>{
        const dbConnect=process.env.MONGODB_URL;
        mongoose.connect(dbConnect,()=>{
        }).then(console.log("database connected"));
        }
        module.exports ={dbconnect};
        
        

        
        MONGODB_URL=mongodb://localhost:27017
    
    
    
    
    
    
        require('dotenv').config();
        const Koa=require('koa');
        const KoaRouter=require('koa-router');
        const cors=require('@koa/cors');
        const bodyParser=require('koa-bodyparser');
        const josn =require('koa-json');
        const { dbconnect } = require('./src/utils/dbconnect');
        const courseRoutes=require("./src/routes/course.routes");
        const studentRoutes=require("./src/routes/student.routes")
        const app= new Koa();
        const router=new KoaRouter();
        app.use(cors());
        app.use(bodyParser());
        app.use(josn());
        app.use(courseRoutes.routes());
        app.use(studentRoutes.routes());
        app.use(router.routes()).use(router.allowedMethods());
        router.get("/",ctx=>{
        ctx.body={message:"student anagement api"}
        })
        app.listen(9000,()=>{
        console.log("server is running on port 9000")
        dbconnect()
        });
    
    
    
    
    
    

        import React from 'react'
        import { useNavigate } from "react-router-dom";
        import { useState } from "react";
        import axios from "axios"
        const Addcourse = () => {
        const[inputs,setinputs]=useState({
        courseName:"",
        coursefees:"",
        }
        );
        const handlchange=(e)=>{
        setinputs((prevState)=>({
        ...prevState,
        [e.target.name]:e.target.value,
        }))
        }
        const sendrequest =async()=>{
        await axios.post("http://localhost:9000/course/add",{
        courseName:String(inputs.courseName),
        coursefees:String(inputs.coursefees),
        }).then((res)=>res.data).then(alert("course data added"))
        }
        const handleSubmit=(e)=>{
        e.preventDefault();
        console.log(inputs);
        sendrequest()
        }
        return (
        <div>
        <form onSubmit={handleSubmit}>
        <h2>Add Course</h2>
        <label >courseName</label><br/>
        <input type="text" name="courseName" value={inputs.courseName}
        onChange={handlchange}/><br/>
        <label >coursefees:</label><br/>
        <input type="text" name="coursefees" value={inputs.coursefees}
        onChange={handlchange}/><br/><br/>
        <button type="submit">submit</button>
        </form>
        <a href='/allCourses'><button>All courses</button></a>
        </div>
        )
        }
        export default Addcourse;
    
    
    
        
        
    
    import{React}  from 'react'
    import axios from 'axios'
    import{useEffect,useState}  from 'react'
    const Allcourses = () => {
    const[coursers,Setcourses]=useState([]);
    const[filtertext,setfiltertext]=useState("");
    useEffect(() => {   
        axios
        .get("http://localhost:9000/course/")
        .then(res=> Setcourses(res.data))
        .catch(error=>console.log(error));
      },[]);
    
     const filteredItems = coursers .filter((supp) =>
     supp.courseName.toLocaleLowerCase().includes(filtertext)
    );
    const fcoursers = filtertext ? filteredItems : coursers;
   
      const onDelete=async(e) =>{
        await axios.delete(`http://localhost:9000/course/${e.target.value}`).then((res) => res.data)
          
     }
      return (
        <div>
    
    <input            type="text"
                     placeholder="Search By CourseName"
                     name="search"
                     onChange={(e) =>
                      setfiltertext(e.target.value.toLocaleLowerCase())
                     }
                   />
    
    
    <h2>All Courses</h2>
    
    <table>
      <tr>
        <th>#</th>
        <th>CourseName</th>
        <th>Coursefees</th>
     
        <th>Acction</th>
      </tr>
    
      { fcoursers.map((course,index) =>(
      <tr key={index 1}>
        <td>{index 1}</td>
        <td>{course.courseName}</td>
        <td>{course.coursefees}</td>
       
     
        <td><a href={`/updatecourse/${course._id}`}><button >update</button> </a>
        <button value={course._id} onClick={onDelete}>delete</button></td>
      </tr>))}
      
    </table>
   </div>
      )
    }
    
    export default Allcourses;
        
        

        
        
        import React from 'react'
        import { useNavigate } from "react-router-dom";
        import { useState } from "react";
        import axios from "axios"
        import { useParams } from 'react-router-dom';
        import { useEffect } from 'react';
        const UpdateCourse = () => {
        const history = useNavigate();
        const id =useParams().id;
        const[inputs,setinputs]=useState({
        courseName:"",
        coursefees:"",
        }
        );
        const handlchange=(e)=>{
        setinputs((prevState)=>({
        ...prevState,
        [e.target.name]:e.target.value,
        }))
        }
        useEffect(() => {
        const fetchHandler = async () => {
        await axios
        .get(`http://localhost:9000/course/${id}`)
        .then((res) =>setinputs(res.data) ) 
        };
        fetchHandler()
        }, [id]);
        const sendrequest =async()=>{
        await axios.put(`http://localhost:9000/course/${id}`,{
        courseName:String(inputs.courseName),
        coursefees:String(inputs.coursefees),
        }).then((res)=>res.data).then(alert("course data added"))
        }
        const handleSubmit=(e)=>{
        e.preventDefault();
        console.log(inputs);
        sendrequest()
        }
        return (
        <div>
        <h2>update Course </h2>
        <div>
        <form onSubmit={handleSubmit}>
        <label >courseName</label><br/>
        <input type="text" name="courseName" value={inputs.courseName}
        onChange={handlchange}/><br/>
        <label >coursefees:</label><br/>
        <input type="text" name="coursefees" value={inputs.coursefees}
        onChange={handlchange}/><br/><br/>
        <button type="submit">submit</button>
        </form>
        <a href='/allCourses'><button>All courses</button></a>
        </div>
        </div>
        )
        }
        export default UpdateCourse
        
        
        
    
    
    
    
        import React from 'react'
        import { useNavigate } from "react-router-dom";
        import { useState } from "react";
        import axios from "axios"
        import { useEffect } from 'react';
        
        const AddStudent = () => {
         const[inputs,setinputs]=useState({
            name:"",
            nic:"",
            age:"",
            courseId:"",
         }
         );
        
         const handlchange=(e)=>{
            setinputs((prevState)=>({
                ...prevState,
                [e.target.name]:e.target.value,
        
            }))
         }
        
         const[courses,Setcourses]=useState([]);
         // const[filtertext,setfiltertext]=useState("");
         useEffect(() => {
               
             axios
             .get("http://localhost:9000/course/")
             .then(res=> Setcourses(res.data))
             .catch(error=>console.log(error));
    
           });
        
        
         const sendrequest  =async()=>{
            await axios.post("http://localhost:9000/student/add",{
               
                name:String(inputs.name),
                nic:String(inputs.nic),
                age:String(inputs.age),
                courseId:String(inputs.courseId)
            }).then((res)=>res.data).then(alert("course data added"))
         }
        
          const handleSubmit=(e)=>{
              e.preventDefault();
              console.log(inputs);
          sendrequest()
          }
        
          return (
            <div>
        <div>
          <form onSubmit={handleSubmit}>
          <h2>Add Course</h2>
          <label >name</label><br/>
          <input type="text"  name="name" value={inputs.name} onChange={handlchange}/><br/>
          <label >nic</label><br/>
          <input type="text" name="nic" value={inputs.nic} onChange={handlchange}/><br/>
          <label >age</label><br/>
          <input type="text" name="age" value={inputs.age} onChange={handlchange}/><br/>
        
          <label >course</label>
          <select name="courseId" onChange={handlchange} ><br/>
          <option value="none" selected disabled hidden>Select a Course</option>
          {courses.map((course, index) => (
                      <option value={course._id} key={index}>
                        {course.courseName}
                      </option>
                    ))}
           
          </select>
          <button type="submit">submit</button>
          </form>
           <a href='/allstudents'><button>All Students</button></a>  
            </div>
        </div>
          )
        }
        export default AddStudent;







import {BrowserRouter as Router ,Routes,Route} from 'react-router-dom'
import './App.css';
import Homepage from './components/homepage';
import Addcourse from './components/course/addcourse';
import Allcourses from './components/course/allcourses';
import UpdateCourse from './components/course/updateCourse';
import AddStudent from './components/student/addStudent';
import AllStudent from './components/student/allStudents';

function App() {
  return (
   <div>
    <Router>
      <Routes>

      <Route path="/" element={<Homepage/>}/>
      <Route path="/addcourse" element={<Addcourse/>}/>
      <Route path="/allCourses" element={<Allcourses/>}/>
      <Route path="/updatecourse/:id" element={<UpdateCourse/>}/>
      <Route path="/addstudents" element={<AddStudent/>}/>
      <Route path="/allstudents" element={<AllStudent/>}/>
      </Routes>

    </Router>

   </div>
  );
}
  • Related