0

I got some servers using Python to insert data to my MongoDB, since I want to read it from old --> new I want to get feedback by increasing number in ID.

I'm using Mongoengine in my python code to insert, but didn't found any information about using MongoDB Javascript functions, such mongo offer Auto-Increment Sequence function in here: https://www.tutorialspoint.com/mongodb/mongodb_autoincrement_sequence.htm

I try to use class like that:

class LogTemplate(mongoengine.Document):
    _id = mongoengine.IntField(required=True)
    logid = mongoengine.IntField(required=True)
    time = mongoengine.DateTimeField(required=True)
    type = mongoengine.IntField(required=True)

Then before save:

def pushToMongo(evtmgr) -> LogTemplate:
    loghand = LogTemplate()
    loghand._id = loghand.getNextSequenceValue('collection name')
    loghand.logid = evtmgr.id
    loghand.type = evtmgr.type
    loghand.time = datetime.fromtimestamp(evtmgr.time.seconds)

But no error, and nothing was insert into DB after that. I'm using Mongo-side increment since more then one server using it.

XDavidT
  • 147
  • 15

1 Answers1

0

There is no support for running mongodb javascript code in mongoengine (beside exec_js that is deprecated and is not suitable for your use case).

That being said, mongoengine provides the SequenceField that could do the trick for your case. It works on the same principle, by storing a counter in a separate collection

e.g:

class Person(Document):
    id = SequenceField(primary_key=True)
    name = StringField()

Person(name='John').save()    # saves {'_id': 1, 'name': 'John'}
Person(name='Bob').save()     # saves {'_id': 2, 'name': 'Bob'}
bagerard
  • 5,681
  • 3
  • 24
  • 48