__How to find the max _id or most recently updated object in collection?__
I'm kind of new to LiteDB.
Got most things working. I can create a POCO, make a db connection and do a collection.Insert().
Now I need to get the most recently added record so I can pull a value from it and increment it in a pattern.
I am struggling with using Queries and Expressions to find the MAX _id item in the collection.
Seems like this should be a pretty common problem but I can't find any examples.
Can someone help?
I just had this problem yesterday
var latest = Coll.FindOne(Query.All(1));
Use -1 to get first item
where coll is your LiteCollection
let me know if that works for you
Hi guys,
First, your poco class will be updated with _id inserted.
Also, Insert method returns this number.
But, as @nh43de say, you can get lower (or highest) value in a index using this command:
var latest = Coll.FindOne(Query.All(Query.Asc));
Hey Thanks!
I'm not used to people replying so quick and with such good options.
Both of these work:
var latest = collection.FindOne(Query.All(-1));
var latest = collection.FindOne(Query.All(Query.Descending));
Makes sense if you think of it as an object store and index rather than a database where you expect a simple MAX(col) function.
Awesome! Glad it worked for you. Also @mbdavid - this is one of the coolest libraries I have come accross in several years. Thank you thank you for you hard work! This library is an amazing alternative to using a MongoDb backend for lightweight applications in .NET
Agree Totally!
I've been using it now for just over a day and have already built an application using it. Great alternative to client-server SQL or NoSQL databases for some applications (like mine - a low use Windows Form application with just local storage needs).
Thanks guys! It's really nice to know about this. I'm still working v5 version that will the a biggest change in this project. In this case, you will resolve this using a single SQL query (or Linq query) like:
SELECT MAX(_id) FROM your_col
or
col.Query().Max(x => x.Id)
As I see in LiteCollection.cs,
// Summary:
// Insert a new entity to this collection. Document Id must be a new value in collection
// - Returns document Id
public BsonValue Insert(T document);
int recentId = -1;
var docId = coll.Insert(info);
if (docId != null) recentId = docId .AsInt32;
@chucksullivancvs it's working for me.
Thanks guys! It's really nice to know about this. I'm still working v5 version that will the a biggest change in this project. In this case, you will resolve this using a single SQL query (or Linq query) like:
SELECT MAX(_id) FROM your_col
or
col.Query().Max(x => x.Id)
That's really cool! Does this mean the IQueryable interface will be implemented?
Hi! With the objective of organizing our issues, we are closing old unsolved issues. Please check the latest version of LiteDB and open a new issue if your problem/question/suggestion still applies. Thanks!