Forum Discussion

elenal's avatar
elenal
Occasional Contributor
7 years ago

Groovy Script to fetch latest document in collection returns inconsistent results

I'm trying to fetch the latest document from MongoDB collection.

The Groovy code is here

@Grab(group='com.gmongo', module='gmongo', version='1.5')

import com.gmongo.GMongo
import com.mongodb.MongoCredential
import com.mongodb.*
import com.mongodb.ServerAddress
import com.gmongo.*
import com.mongodb.MongoURI
import com.mongodb.DBCursor;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBList

def mongoendpoint = context.expand( '${#Project#mongoendpoint}' )
def mongocollection=context.expand( '${#Project#mongocollection_jobs}' )
def mongo= new GMongo (new MongoURI(mongoendpoint))

def db = mongo.getDB(mongocollection)
def collection = db.getCollection("**")


DBCursor test = db.**.find().sort($natural:-1).limit(1);
if (test.hasNext() )
{
DBObject obj = test.next()
String res=obj._id
log.info(res)

}

My problem is that results I'm getting are inconsistent, e.g. if I run script multiple time, approximately half of the times I'm getting correct document and half - another document, which if for sure not latest.

 

If I run the same query from mongo shell results are pretty consistent and correct.

 

Have anyone seen that before? Trying to understand if there's any error in my code etc...

Thanks

No RepliesBe the first to reply