如何创建一个随机的unice Id mongoDb



在我的最后一个项目中,我正在为Car repairment Garages做一个简单的Manager应用程序,为DB我正在使用MongoDB,我看到了Tim corny的一个很棒的教程,但我不知道如何为每个对象生成Unice Id。

这是我的类数据库中每个对象的操作

public class MongoActions
{
private static Random random;
public static void UpsertRecord<T>(int id, string table, T record)
{
var collection =  Mongo.db.GetCollection<T>(table);
var result = collection.ReplaceOne(
new BsonDocument("_id", id),
record,
new UpdateOptions { IsUpsert = true }
);
}
public static int RandomId<T>(string table)
{
**//how to find a nice Id that is not repeated** 

}   
public static void  InsertRecord<T>(string table, T record)
{
var collection = Mongo.db.GetCollection<T>(table);
collection.InsertOne(record);
}
public static T FindRecord<T>(string table, string field, string value)
{
var collection = Mongo.db.GetCollection<T>(table);
var fillter = Builders<T>.Filter.Eq(field, value);
return collection.Find(fillter).First();
}
public static List<T> FillterRecords<T>(string table, string field, string value)
{
var collection = Mongo.db.GetCollection<T>(table);
var fillter = Builders<T>.Filter.Eq(field, value);
return collection.Find(fillter).ToList();
}
public static List<T> LoadRecords<T>(string table)
{
var collection = Mongo.db.GetCollection<T>(table);
return collection.Find(new BsonDocument()).ToList();
}
public static void DeleteRecord<T>(string table,int id)
{
var collection = Mongo.db.GetCollection<T>(table);
var fillter = Builders<T>.Filter.Eq("_id", id);
collection.DeleteOne(fillter);
}
}

这是连接类

public static class Mongo
{
public static string database = "Garage";
public static MongoClient client=new MongoClient();
public static IMongoDatabase db = client.GetDatabase(database);
}

如果有人帮我,我会很高兴

将您的Id更改为ObjectId,并且不要在插入之前设置它,这样数据库引擎将在您的行为上设置它,并在您的对象上设置它:

签出以下代码:

class Order
{
public ObjectId Id { get; set; }
public string Name { get; set; }
}
var client = new MongoClient();
var database = client.GetDatabase("test");
var collection = database.GetCollection<Order>("orders");
// Leave the Id on Order as `null`
var myOrder = new Order {Name = "My Order"};
// Once we insert the Order the Id will be set.
await collection.InsertOneAsync(myOrder);
Console.WriteLine($"Order Id: {myOrder.Id}"); // Order Id: 5edbb15c75e67361d07362c2
Console.WriteLine($"Order Id: {myOrder.Name}"); // Order Id: My Order

最新更新