Calling Javascript function from pymongo

Hi Folks ,

I have a function

  function getStudentSequence(sequenceName) {
        var result = db.short_counter.findAndModify(
         {
          query: { _id: sequenceName },
          update: { $inc: { seq: 1 } },
          new: true
         }
        );
        return result.seq;
       }

I am able to execute this function with mongo shell like this

 db.short.insert(
        {
              _id: getStudentSequence("rollNo"),
              long_url: "www.google.com"
          
         }

I would like to execute the same using pymongo from jupyter notebook.

please advice

Why not? I just converted JavaScript to Python function, and it works for me…

def get_student_sequence(sequence_name):

    updated_record = db.short_counter.find_one_and_update(filter={"_id": sequence_name},
                                                          upsert=True, update={"$inc": {"seq": 1}},
                                                          return_document=True)
    return f"{updated_record['seq']}"

db.short.insert_one({"_id": get_student_sequence("rollNo"), "long_url": "www.google.com")})
1 Like