Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In litedb,How can I get the _id value?

Tags:

litedb

As shown below, I inserted an element into the document, and it automatically generated an _id of type Object for me. So how do I use the existing model to get the value of this _id?

using LiteDB;

using (var db = new LiteDatabase(@"C:\litedb\test.db"))
{
    var accountCollection = db.GetCollection<Account>("Account");
    Account account = new Account
    {
        Username = "root",
        Password = "123456"
    };
    accountCollection.Insert(account);
    //{
    //    "_id": { "$oid": "642ec0a9f6aecc035cd15f5e"},
    //  "Username": "root",
    //  "Password": "123456"
    //}
}

public class Account
{
    public string? Username { get; set; }
    public string? Password { get; set; }
}

I want to get the _id value 642ec0a9f6aecc035cd15f5e Is there any way?

like image 703
Nyakohub Avatar asked Sep 16 '25 21:09

Nyakohub


1 Answers

you can try in this way instead.

Insert in your model the ID property also.

public class Account
{
    public Guid ID {get;set;}

    public string? Username { get; set; }
    public string? Password { get; set; }
}

Then generate a new ID.

using (var db = new LiteDatabase(@"C:\litedb\test.db"))
{
    var accountCollection = db.GetCollection<Account>("Account");

    Account account = new Account
    {
        ID = Guid.NewGuid(),
        Username = "root",
        Password = "123456"
    };    

    accountCollection.Insert(account);

    Console.WriteLine(account.ID.ToString());
}

From LiteDB documentation AutoId is only used when there is no _id field in the document upon insertion.

like image 66
Alessandro Gaspani Avatar answered Sep 23 '25 11:09

Alessandro Gaspani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!