在LiteDB中,如何获取_id的值?

huangapple go评论111阅读模式
英文:

In litedb,How can I get the _id value?

问题

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

英文:

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?

答案1

得分: 1

你可以尝试以这种方式进行。

在你的模型中插入ID属性也。

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

然后生成一个新的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());
}

LiteDB文档中了解,AutoId只在文档插入时没有_id字段时使用。

英文:

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(@&quot;C:\litedb\test.db&quot;))
{
    var accountCollection = db.GetCollection&lt;Account&gt;(&quot;Account&quot;);

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

    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.

huangapple
  • 本文由 发表于 2023年4月6日 21:02:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75949846.html
  • litedb
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定