Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find max in a MongoDB collection using .Net Driver 2

With the 1.10 version of the .NET driver I could do something like this to get the max timestamp in the oplog collection:

this.oplogCollection.AsQueryable<OplogEntry>().Max(o => o.ts);

How can I do that with the new driver 2.0? The documentation is basically non-existent or not helpful, so I am hoping some insiders can shed some light here.

like image 629
hholtij Avatar asked Apr 08 '15 00:04

hholtij


People also ask

How do I check the size of a file in MongoDB?

If you need to return the size of a document in MongoDB, you can use the following: The $bsonSize aggregation pipeline operator. The Object. bsonSize() method.

How do I query a collection in MongoDB?

To query data from MongoDB collection, you need to use MongoDB's find() method.

How do I find a specific data in MongoDB?

In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents. Cursor means a pointer that points to a document, when we use find() method it returns a pointer on the selected documents and returns one by one.


1 Answers

You can try this:

var result = await collection.Find(x => true).SortByDescending(d => d.ts).Limit(1).FirstOrDefaultAsync();

BTW $max doesn't give you the biggest value as in Linq or SQL, it specifies the upper exclusive bound of a Find. Documentation here

like image 178
D.Rosado Avatar answered Oct 12 '22 20:10

D.Rosado