Skip to content
Advertisement

Perform $gte and $lt on the same field _id in MongoDB

db.comments.find({"_id" : {"$gte": ObjectId("6225f932a7bce76715a9f3bd"), "$lt":ObjectId("6225f932a7bce76715a9f3bd")}}).sort({"created_datetime":1}).limit(10).pretty()

I am using this query which should give me the current “6225f932a7bce76715a9f3bd” doc, 4 docs inserted before this and 5 docs inserted after this. But currently when i run this query, i get null result. Where am i going wrong ??

Advertisement

Answer

I had no other option but to seperate my queries in order to achieve my expectation.

        query = request.args.to_dict()
        find_query = {}
        find_query["_id"] = {"$lt": ObjectId(query["comment_id"])}
        previous_comments = list(db.comments.find(find_query))
        find_query["_id"] = {"$gte": ObjectId(query["comment_id"])}
        next_comments =  list(db.comments.find(find_query))
        previous_comments.extend(next_comments)
        return {"comments":previous_comments} 
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement