简体   繁体   中英

Inserting documents in MongoDB in specific order using pymongo

I have to insert documents in MongoDB in a left-shift manner ie if the collection contains 60 documents, I am removing the 1st document and I want to insert the new document at the rear of the database. But when I am inserting the 61st element and so forth, the documents are being inserted in random positions. Is there any way I can insert the documents in the order that I specified above? Or do I have to do this processing when I am retrieving the values from the database? If yes then how? The data format is :

data = {"time":"10:14:23", #timestamp 
         "stats":[<list of dictionaries>]
       } 

The code I am using is

from pymongo import MongoClient
db = MongoClient().test
db.timestamp.delete_one({"_id":db.timestamp.find()[0]["_id"]})
db.timestamp.insert_one(new_data)

the timestamp is the name of the collection.

Edit: Changed the code. Is there any better way?

from pymongo.operations import InsertOne,DeleteOne

def save(collection,data,cap=60):
    if collection.count() == cap:
        top_doc_time= min(doc['time'] for doc in collection.find())
        collection.delete_one({'time':top_doc_time['_time']})
    collection.insert_one(data)

A bulk write operation guarantees query ordering by default . This means that the queries are executed sequentially.

from pymongo.operations import DeleteOne, InsertOne


def left_shift_insert(collection, doc, cap=60):
    ops = []
    variance = max((collection.count() + 1) - cap, 0)
    delete_ops = [DeleteOne({})] * variance
    ops.extend(delete_ops)
    ops.append(InsertOne(doc))

    return collection.bulk_write(ops)

left_shift_insert(db.timestamp, new_data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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