Get the value of a field for the latest record in a collection

38 Views Asked by At

I have a collection rawUnits. I am getting the latest record from this collection using

db.getCollection('rawUnits').find().limit(1).sort({$natural:-1})

This gives me the record which has a nested field saleinfo.group.id I want to get the value for this field how do I do that?

1

There are 1 best solutions below

1
nimrod serok On

You can $project it:

db.getCollection('rawUnits').find({}, {'saleinfo.group.id':1}).limit(1).sort({$natural:-1})

But it is better to limit your search, if you filter by any field...